在某些情況下(例如通過網絡訪問數據),常常不希望程序卡住而占用太多時間以至於造成界面假死。
在這時、我們可以通過Thread、Thread + Invoke(UI)或者是 delegate.BeginInvoke 來避免界面假死,
但是這樣做時,某些代碼或者是某個方法的執行超時的時間還是無法操控的。
那么我們又是否有一種比較通用的方法、來設定某一個方法的執行超時的時間,讓其一旦超過指定時間則跳出指定方法、進而繼續向下執行呢?
答案當然是肯定的。
delegate.BeginInvoke可以實現代碼代碼的異步執行,在這種情況下,只要讓程序可以等待一個Timespan,如果在Timespan到達之前方法內的代碼還沒有執行完畢、說明該方法執行超時了。
那么關鍵的就是“等待一個Timespan”,而恰好.NET 里提供了一些類和方法來實現該功能。我這里選用的是ManualResetEvent.WaitOne(timespan, false);其返回值代碼其是否在特定時間內收到信號,而我們恰好可以利用這個布爾值 外加一個標記變量 來判斷一個方法是否執行超時。
相關的實現代碼如下:

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(); } } }
調用:

private static Stopwatch watch; private static System.Threading.Timer timer; static void 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(); } static void timerCallBack(object obj) { Console.WriteLine(string.Format("運行時間:{0}秒", watch.Elapsed.TotalSeconds.ToString("F2"))); } public void DoSomething() { // 休眠 5秒 System.Threading.Thread.Sleep(new TimeSpan(0, 0, 0, 5)); }
地址:http://www.cnblogs.com/08shiyan/archive/2011/07/30/2122183.html