C# 自定义超时执行实现

参考: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();
            }
posted @ 2018-10-23 15:38  流浪者的飘  阅读(4228)  评论(0编辑  收藏  举报