如何做设置超时的方法 [英] how do set a timeout for a method

查看:131
本文介绍了如何做设置超时的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置一个繁忙的方法+ C#超时。

how do set a timeout for a busy method +C#.

推荐答案

好吧,这里是真正的答案。

Ok, here's the real answer.

...

void LongRunningMethod(object monitorSync)
{
   //do stuff    
   lock (monitorSync) {
     Monitor.Pulse(monitorSync);
   }
}

void ImpatientMethod() {
  Action<object> longMethod = LongRunningMethod;
  object monitorSync = new object();
  bool timedOut;
  lock (monitorSync) {
    longMethod.BeginInvoke(monitorSync, null, null);
    timedOut = !Monitor.Wait(monitorSync, TimeSpan.FromSeconds(30)); // waiting 30 secs
  }
  if (timedOut) {
    // it timed out.
  }
}

   ...



这种结合了两种使用C#中最有趣的部分。首先,异步调用该方法,使用具有花哨的裤子的BeginInvoke 魔法的委托。

然后,使用显示器从 LongRunningMethod ImpatientMethod 来让它知道当它完成,或发送邮件如果它不是来自它在一定的时间听说了,干脆放弃它。

Then, use a monitor to send a message from the LongRunningMethod back to the ImpatientMethod to let it know when it's done, or if it hasn't heard from it in a certain amount of time, just give up on it.

(PS-开玩笑这个是真正的答案。我知道,有2 ^ 9303的方式来皮肤猫,尤其是在.NET)

(p.s.- Just kidding about this being the real answer. I know there are 2^9303 ways to skin a cat. Especially in .Net)

这篇关于如何做设置超时的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆