C#如何控制方法的執行時間,超時則強制退出方法執行

有時候我們需要控制方法的執行時間,如果超時則強制退出。

要控制執行時間,我們必須使用異步模式,在另外一個線程中執行方法,如果超時,則拋出異常終止線程執行。

如下使用異步執行委託的方式實現,使用WaitHandle的WaitOne方法來計算時間超時:

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


發佈了11 篇原創文章 · 獲贊 9 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章