日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

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

發布時間:2025/4/5 C# 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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#如何控制方法的执行时间,超时则强制退出方法执行的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。