如何估计方法执行时间?
答
check if network drive exists with timeout in c#
https://web.archive.org/web/20140222210133/http://kossovsky.net/index.php/2009/07/csharp-how-to-limit-method-execution-time
异步模式:
public static T SafeLimex<T>(Func<T> F, int Timeout, out bool Completed)
{
var iar = F.BeginInvoke(null, new object());
if (iar.AsyncWaitHandle.WaitOne(Timeout))
{
Completed = true;
return F.EndInvoke(iar);
}
F.EndInvoke(iar); //not calling EndInvoke will result in a memory leak
Completed = false;
return default(T);
}
答
您应该在两秒钟内创建System.Threading.Timer,然后在另一个线程中运行您的方法,并等待它的回调,如果方法在定时器运行之前完成,则应该处理定时器,否则应该中止您的方法正在执行。例如,这是
using (new Timer(BreakFunction, true, TimeSpan.FromMinutes(2), Timeout.Infinite))
{
//TODO:here you should create another thread that will run your method
}
很简单,在BreakFunction你应该中止运行你的方法
答
线程这将是很好的,如果你能找到它。我一直在寻找它。
我通常做的是在另一个Thread
开始方法,并在这种情况下开始Timer
2秒。它会引发事件的第一次,只是做:
if (a.IsAlive)
{
a.Abort();
}
两个重要的事情:
- 声明应该由一个处理计时器
- 当调用
Abort()
方法是可见的Thread
,它提出ThreadAbortException,所以你应该在方法中正确处理它。
你为什么不启动它从一开始另一个线程? – 2011-02-17 05:53:40
我真的不认为有任何简单的方法*精确*做你的要求。你需要在整个地方插入钩子。你为什么坚持首先在调用线程上调用该方法? – Ani 2011-02-17 06:10:03