线程运行超时处理类

线程运行超时处理类

    public class TimeoutChecker
    {
        #region /*private member*/

        long _timeout; //超时时间
        System.Action<Delegate> _proc;//会超时的代码
        System.Action<Delegate> _procHandle;//处理超时
        System.Action<Delegate> _timeoutHandle;//超时后处理事件
        System.Threading.ManualResetEvent _event = new System.Threading.ManualResetEvent(false);

        #endregion

        #region /*constructor method*/

        /// <summary>
        /// 构选方法
        /// </summary>
        /// <param name="proc">会超时的代码</param>
        /// <param name="timeoutHandle">超时后处理事件</param>
        public TimeoutChecker(System.Action<Delegate> proc, System.Action<Delegate> timeoutHandle)
        {
            this._proc = proc;
            this._timeoutHandle = timeoutHandle;
            this._procHandle = delegate
            {
                //计算代码执行的时间
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                sw.Start();
                if (this._proc != null)
                    this._proc(null);
                sw.Stop();
                //如果执行时间小于超时时间则通知用户线程
                if (sw.ElapsedMilliseconds < this._timeout && this._event != null)
                {
                    this._event.Set();
                }
            };
        }

        #endregion

        #region /*public method*/

        /// <summary>
        /// 等待执行
        /// </summary>
        /// <param name="timeout">等待时间毫秒</param>
        /// <returns></returns>
        public bool Wait(long timeout)
        {
            this._timeout = timeout;
            //异步执行
            this._procHandle.BeginInvoke(null, null, null);
            //如果在规定时间内没等到通知则为 false
            bool flag = this._event.WaitOne((int)timeout, false);
            if (!flag)
            {
                //触发超时时间
                if (this._timeoutHandle != null)
                    this._timeoutHandle(null);
            }
            this.Dispose();

            return flag;
        }

        #endregion

        #region private method

        /// <summary>
        /// 释放资源
        /// </summary>
        private void Dispose()
        {
            if (this._event != null)
                this._event.Close();
            this._event = null;
            this._proc = null;
            this._procHandle = null;
            this._timeoutHandle = null;
        }

        #endregion
    }

调用

 

 TimeoutChecker timeout = new TimeoutChecker(
                    delegate
                    {
                        
                        try
                        {
                            //把耗时的处理加到这里
                           
                        }
                        catch (Exception he)//异常处理
                        {
                           
                        }
                    },
                    delegate//超时处理
                    {
                     
                    });

                // 按毫秒等待
                // 执行成功的处理,且未超时
                if (timeout.Wait(10000))
                {
                    Console.WriteLine("WaitTimes: {0}", DateTime.Now.ToString());
                }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/110454.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • hashmap扩容死锁简书_sql死锁

    hashmap扩容死锁简书_sql死锁HashMap扩容HashMap扩容transfer()函数原Entry数组转移到新Entry数组扩容死锁单线程扩容多线程扩容死锁HashMap扩容HashMap在JDK1.7使用的是数组+链表的方式,而在JDK1.8及以后则使用的是数组+链表+红黑树的方式进行数据存储。本文主要是对JDK1.7中存在的死锁问题进行分析。transfer()函数/***TransfersallentriesfromcurrenttabletonewTable.*/v

    2022年9月21日
    2
  • SVN的学习.SVN的使用方式!TortoiseSVN以及TortoiseSVN汉化包下载和使用!

    一.SVN是什么:SVN是Subversion的简称,是一个开放源代码的版本控制系统,说得简单一点SVN就是用于多个人共同开发同一个项目,共用资源的目的。二.SVN的工作流程:集中式管理的工作流程:集中式代码管理的核心是服务器,所有开发者在开始新一天的工作之前必须从服务器获取代码,然后开发,最后解决冲突,提交。所有的版本信息都放在服务器上。如果脱离了服务器,开发者…

    2022年4月10日
    34
  • 使用DatagramSocket发送、接收数据(Socket之UDP套接字)

    使用DatagramSocket发送、接收数据(Socket之UDP套接字)http://book.51cto.com/art/201203/322540.htm17.4.2使用DatagramSocket发送、接收数据(1)Java使用DatagramSocket代表UDP协议的Socket,DatagramSocket本身只是码头,不维护状态,不能产生IO流,它的唯一作用就是接收和发送数据报,Java使用DatagramPacket来代表数据报,Datagr

    2022年6月12日
    93
  • java设置content type_Response Content Type设置[通俗易懂]

    java设置content type_Response Content Type设置[通俗易懂]1.常见的contenttype:.aiff=audio/aiff.anv=application/x-anv.asa=text/asa.asf=video/x-ms-asf.asp=text/asp.asx=video/x-ms-asf.au=audio/basic.avi=video/avi.awf=application/vnd.adobe.workfl…

    2022年7月19日
    87
  • 软件安装管家【软件目录】[通俗易懂]

    https://blog.csdn.net/luai_l/article/details/106318576

    2022年4月18日
    75
  • headless CMS_model view controller

    headless CMS_model view controller目录介绍HeadlessCMS什么是HeadlessCMS?HeadlessCMS的优点HeadlessCMS解决方案的局限性使用HCMS的缺点HCMS的局限性何时何地使用HeadlessCMS?RawCMS:构建自己的HeadlessCMS为什么另一个HeadlessCMS?RawCms特征选择架构服务层认证Lambda表…

    2025年5月30日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号