C# 給某個方法設定執行超時時間
阿新 • • 發佈:2018-12-30
在某些情況下(例如通過網路訪問資料),常常不希望程式卡住而佔用太多時間以至於造成介面假死。
在這時、我們可以通過Thread、Thread + Invoke(UI)或者是 delegate.BeginInvoke 來避免介面假死,
但是這樣做時,某些程式碼或者是某個方法的執行超時的時間還是無法操控的。
那麼我們又是否有一種比較通用的方法、來設定某一個方法的執行超時的時間,讓該其一旦超過指定時間則跳出指定方法、進而繼續向下執行呢?
答案當然是肯定的。
delegate.BeginInvoke可以實現程式碼程式碼的非同步執行,在這種情況下,只要讓程式可以等待一個Timespan,如果在Timespan到達之前方法內的程式碼還沒有執行完畢、說明該方法執行超時了。
那麼關鍵的就是“等待一個Timespan”,而恰好.NET 裡提供了一些類和方法來實現該功能。我這裡選用的是ManualResetEvent.WaitOne(timespan, false);其返回值程式碼其是否在特定時間內收到訊號,而我們恰好可以利用這個布林值 外加一個標記變數 來判斷一個方法是否執行超時。
相關的實現程式碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace Common { public delegate void DoHandler(); public class Timeout { private ManualResetEvent mTimeoutObject; //標記變數 private bool mBoTimeout; public DoHandler Do; public Timeout() { // 初始狀態為 停止 this.mTimeoutObject = new ManualResetEvent(true); } ///<summary> /// 指定超時時間 非同步執行某個方法 ///</summary> ///<returns>執行 是否超時</returns> public bool DoWithTimeout(TimeSpan timeSpan) { if (this.Do == null) { return false; } this.mTimeoutObject.Reset(); this.mBoTimeout = true; //標記 this.Do.BeginInvoke(DoAsyncCallBack, null); // 等待 訊號Set if (!this.mTimeoutObject.WaitOne(timeSpan, false)) { this.mBoTimeout = true; } return this.mBoTimeout; } ///<summary> /// 非同步委託 回撥函式 ///</summary> ///<param name="result"></param> private void DoAsyncCallBack(IAsyncResult result) { try { this.Do.EndInvoke(result); // 指示方法的執行未超時 this.mBoTimeout = false; } catch (Exception ex) { Console.WriteLine(ex.Message); this.mBoTimeout = true; } finally { this.mTimeoutObject.Set(); } } } }
測試程式碼如下:
class Program { privatestatic Stopwatch watch; privatestatic System.Threading.Timer timer; [STAThread] staticvoid Main(string[] args) { watch =new Stopwatch(); Timeout timeout =new Timeout(); timeout.Do =new Program().DoSomething; watch.Start(); timer =new System.Threading.Timer(timerCallBack, null, 0, 500); Console.WriteLine("4秒超時開始執行"); bool bo = timeout.DoWithTimeout(new TimeSpan(0, 0, 0, 4)); Console.WriteLine(string.Format("4秒超時執行結果,是否超時:{0}", bo)); Console.WriteLine("***************************************************"); timeout =new Timeout(); timeout.Do =new Program().DoSomething; Console.WriteLine("6秒超時開始執行"); bo = timeout.DoWithTimeout(new TimeSpan(0, 0, 0, 6)); Console.WriteLine(string.Format("6秒超時執行結果,是否超時:{0}", bo)); timerCallBack(null); watch.Stop(); timer.Dispose(); Console.ReadLine(); } staticvoid timerCallBack(object obj) { Console.WriteLine(string.Format("執行時間:{0}秒", watch.Elapsed.TotalSeconds.ToString("F2"))); } publicvoid DoSomething() { // 休眠 5秒 System.Threading.Thread.Sleep(new TimeSpan(0, 0, 0, 5)); } }