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

相關文章
相關標籤/搜索