C # Implementation of custom timeout execution

reference resources: https://blog.csdn.net/educast/article/details/7430932

Because some methods may prevent threads from continuing to execute, it is necessary to define a timeout prevention method, and you can get whether or not to timeout. When timeout occurs, you can perform certain operations;

Main code:

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

Call method:

This application scenario will appear because the Excel file has been damaged. The "Problems during Loading" dialog box cannot be hidden for the time being. Therefore, if a timeout occurs, the Excel process will be closed actively to prevent the current thread from being blocked and cannot continue;

 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(); }
posted @ 2018-10-23 15:38   Wanderer's Gone with the Wind   Reading( four thousand two hundred and twenty-nine Comments( zero edit   Collection   report