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

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

 

有时候咱们须要控制方法的执行时间,若是超时则强制退出。异步

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

以下实现的方法:this

class Program { static void Main(string[] args) { //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); } else { threadToKill.Abort(); throw new TimeoutException(); } } }

上例中使用异步执行委托的方式实现,使用WaitHandle的WaitOne方法来计算时间超时。spa

相关文章
相关标签/搜索