參考:https://blog.csdn.net/educast/article/details/7430932
由於某些方法可能產生阻止線程繼續執行,需要定義防止超時,且可以得到是否超時,超時可執行某些操作;
主要代碼:
public delegate void DoHandler(object obj);
public class TimeoutHelper
{
private ManualResetEvent mTimeoutObject;
//標記變量
private bool mBoTimeout;
/// <summary>
/// 可能超時要異步執行的方法
/// </summary>
public DoHandler Do;
public TimeoutHelper()
{
// 初始狀態為 停止
this.mTimeoutObject = new ManualResetEvent(true);
}
/// <summary>
/// 指定超時時間 異步執行某個方法
/// </summary>
/// <param name="timeSpan">超時時間</param>
/// <param name="objParam">執行方法參數對象</param>
/// <returns>執行 是否超時</returns>
public bool DoWithTimeout(TimeSpan timeSpan, object objParam)
{
if (this.Do == null)
{
return false;
}
this.mTimeoutObject.Reset();
this.mBoTimeout = true; //標記
this.Do.BeginInvoke(objParam, 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();
}
}
}
調用方法:
本應用場景因為excel文件已經破壞會出現,“加載期間出現問題”對話框,暫時無法隱藏,故若出現超時,則主動關閉Excel進程,防止當前線程被一直阻止,無法繼續進行;
TimeoutHelper timeHelper = new TimeoutHelper();
timeHelper.Do = this.ConvertExcel;
if (timeHelper.DoWithTimeout(new TimeSpan(0, 0, 0, 5), filePath)==false)
{//若文件被破壞且轉換超時,則主動關閉excel的進程
this.KillExcel();
}
