C#如何控制方法的执行时间,超时则强制退出方法执行

转载: http://outofmemory.cn/code-snippet/1762/C-how-control-method-zhixingshijian-chaoshi-ze-force-quit-method-execution/comments1

http://www.cnblogs.com/08shiyan/archive/2011/07/30/2122183.html

C#实现带有超时功能的回调函数类

http://www.blue1000.com/bkhtml/c17/2013-01/71047.htm

有时候我们需要控制方法的执行时间,如果超时则强制退出。

要控制执行时间,我们必须使用异步模式,在另外一个线程中执行方法,如果超时,则抛出异常终止线程执行。

如下实现的方法:

//try the five second method with a 6 second timeout CallWithTimeout(FiveSecondMethod, 6000); //try the five second method with a 4 second timeout //this will throw a timeout exception CallWithTimeout(FiveSecondMethod, 4000); static void FiveSecondMethod() Thread.Sleep(5000); static void CallWithTimeout(Action action, int timeoutMilliseconds) Thread threadToKill = null; Action wrappedAction = () => threadToKill = Thread.CurrentThread; action(); IAsyncResult result = wrappedAction.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) wrappedAction.EndInvoke(result); threadToKill.Abort(); throw new TimeoutException();