C # Implementation of custom timeout execution
public delegate void DoHandler(object obj); public class TimeoutHelper { private ManualResetEvent mTimeoutObject; //Tag variable private bool mBoTimeout; /// <summary> ///Possible timeout Method to be executed asynchronously /// </summary> public DoHandler Do; public TimeoutHelper() { //The initial state is stop this.mTimeoutObject = new ManualResetEvent(true); } /// <summary> ///Specify timeout to execute a method asynchronously /// </summary> ///<param name="timeSpan">Timeout</param> ///<param name="objParam">Execute Method Parameter Object</param> ///<returns>Time out of execution</returns> public bool DoWithTimeout(TimeSpan timeSpan, object objParam) { if (this.Do == null) { return false; } this.mTimeoutObject. Reset(); this.mBoTimeout = true; // Mark this. Do.BeginInvoke(objParam, DoAsyncCallBack, null); //Waiting signal set if (!this.mTimeoutObject.WaitOne(timeSpan, false)) { this.mBoTimeout = true; } return this.mBoTimeout; } ///<summary> ///Asynchronous delegate callback function ///</summary> ///<param name="result"></param> private void DoAsyncCallBack(IAsyncResult result) { try { this. Do.EndInvoke(result); //Indicates that the execution of the method has not timed out this.mBoTimeout = false; } catch (Exception ex) { Console. WriteLine(ex.Message); this.mBoTimeout = true; } finally { this.mTimeoutObject. Set(); } } }
TimeoutHelper timeHelper = new TimeoutHelper(); timeHelper. Do = this. ConvertExcel; if (timeHelper.DoWithTimeout(new TimeSpan(0, 0, 0, 5), filePath)==false) {//If the file is damaged and the conversion times out, the Excel process will be closed this. KillExcel(); }