有時候我們需要控制方法的執行時間,如果超時則強制退出。
要控制執行時間,我們必須使用異步模式,在另外一個線程中執行方法,如果超時,則拋出異常終止線程執行。
如下使用異步執行委託的方式實現,使用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();
}
}}