C#如何控制方法的执行时间,超时则强制退出方法执行
生活随笔
收集整理的這篇文章主要介紹了
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
有時候我們需要控制方法的執行時間,如果超時則強制退出。
要控制執行時間,我們必須使用異步模式,在另外一個線程中執行方法,如果超時,則拋出異常終止線程執行。
如下實現的方法:
class Program {static void Main(string[] args){//try the five second method with a 6 second timeoutCallWithTimeout(FiveSecondMethod, 6000);//try the five second method with a 4 second timeout//this will throw a timeout exceptionCallWithTimeout(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();}}} View Code?
總結
以上是生活随笔為你收集整理的C#如何控制方法的执行时间,超时则强制退出方法执行的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式之桥接模式实例
- 下一篇: SQL Server事务