如何估计方法执行时间?
问题描述:
我需要取消方法执行,如果它需要两秒钟以上完成和在另一个线程重新启动它。
I have requirement to cancel method execution if it takes the more than two seconds to complete and restart it on another thread.
所以,有没有任何方式/
So, is there any way/call back mechanism/HACK, I can make method inform me that it crossed 2 seconds time limit?
答
检查网络驱动器是否存在,并在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);
}