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

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();
                }
            };            
        }
        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;
        }        
        private void Dispose()
        {       
            if(this._event != null)
                this._event.Close();
            this._event = null;
            this._proc = null;
            this._procHandle = null;
            this._timeoutHandle = null;              
        }        
    }

调用超时处理方法:

/// <summary>
        /// 检查摄像头是否可用
        /// </summary>
        /// <param name="device">所选设备</param>
        /// <param name="image">摄像头输出,用于判断</param>
        /// <returns>image不为空摄像头可用,否则不可用</returns>
        public bool isCameraWork(Camera device, NImage image)
        {
            try
            {
                device.StartCapturing();
                TimeoutChecker timeout = new TimeoutChecker(
                    delegate
                    {
                        try
                        {
                            image = device.GetCurrentFrame();
                        }
                        catch
                        {
                            image = null;
                            nlView.Image = null;
                        }
                    },
                    delegate
                    {
                        Console.WriteLine(device.ToString() + "获取设备超时");
                    });
                if (timeout.Wait(1000))
                    Console.WriteLine(device.ToString() + " 设备获取成功");
            }
            catch (Exception e)
            {
                image = null;
                Console.WriteLine(device.ToString() + e.Message);
            }
            device.StopCapturing();
            if (image != null)
                return true;
            else
                return false;
        }

C#超时处理(转载)的更多相关文章

  1. ajax请求超时判断(转载)

    ajax请求时有个参数可以借鉴一下 var ajaxTimeOut = $.ajax({ url:'', //请求的URL timeout : 1000, //超时时间设置,单位毫秒 type : ' ...

  2. 如何设置ASP.NET页面的运行超时时间 (转载)

    全局超时时间 服务器上如果有多个网站,希望统一设置一下超时时间,则需要设置 Machine.config 文件中的 ExecutionTimeout 属性值.Machine.config 文件位于 % ...

  3. [ 转载]JAVA Socket超时浅析

    JAVA Socket超时浅析 转载自 http://blog.csdn.net/sureyonder/article/details/5633647 套接字或插座(socket)是一种软件形 式的抽 ...

  4. libcurl网络连接使用tcp/ip

    CURL *curl; CURLcode res; const char *request = "GETas.xxxxE测试发送"; curl_socket_t sockfd; / ...

  5. python urllib2介绍

    urllib2是Python的一个获取URLs(Uniform Resource Locators)的组件.他以urlopen函数的形式提供了一个非常简单的接口, 这是具有利用不同协议获取URLs的能 ...

  6. Linux系统出现hung_task_timeout_secs和blocked for more than 120 seconds的解决方法

    Linux系统出现系统没有响应. 在/var/log/message日志中出现大量的 “echo 0 > /proc/sys/kernel/hung_task_timeout_secs" ...

  7. 【转载】Extjs设置Ajax请求的超时时间timeout

    在Extjs中的Ajax请求中,Ext.Ajax.request 默认超时时间是30秒,有时候我们有比较耗时的操作需要设置更长时间,此时我们就需要修改Ext.Ajax.Requset的超时时间为更长, ...

  8. druid socket timeout超时15分钟(转载)

    背景 在应用端通过mybatis的interceptor自定义Plugin拦截Executor, 统计输出sql的执行耗时. 今天生产发生一个很奇怪的问题: 莫名其妙卡顿15分钟+,其后正常返回sql ...

  9. 如何设置ASP.NET页面的运行超时时间 (转载)

    全局超时时间 服务器上如果有多个网站,希望统一设置一下超时时间,则需要设置 Machine.config 文件中的 ExecutionTimeout 属性值. Machine.config 文件位于 ...

随机推荐

  1. 听同事讲 Bayesian statistics: Part 1 - Bayesian vs. Frequentist

    听同事讲 Bayesian statistics: Part 1 - Bayesian vs. Frequentist   摘要:某一天与同事下班一同做地铁,刚到地铁站,同事遇到一熟人正从地铁站出来. ...

  2. UIImageView之我的动画为什么停了?UIImageView, highLighted,animationImages

    如果你的动画总是停了!停了!停了!不管你想不想都停,这里有个参考,你可以看看!这只是一种可能性!!! 受最近看到段子影响,画风略诡异,不喜勿喷. 最近在“刻”动画!!! 为什么是“刻”,动画写了3周啊 ...

  3. JSP页面间传递参数的5种方法

    JSP页面间传递参数是经常需要使用到的功能,有时还需要多个JSP页面间传递参数.下面介绍一下实现的方法. (1)直接在URL请求后添加 如:< a href="thexuan.jsp? ...

  4. 又拍云——图像处理师(GraphicsMagick、ImageMagick、FFmpeg)

    云处理平台开发工程师 工作地:杭州 岗位职责:负责云处理平台研发工作: 岗位要求: 扎实的 C 语言编程基础及算法优化能力: 至少能够熟练使用一门脚本语言(Python.Ruby.Lua 等)进行日常 ...

  5. 修改表增加字段默认值default

    对个生产库的表增加1个字段.字段类型是INT型, 表数据有2千万条, alter table table_name add xxoo number(4) default  0 ; 因此 不仅要修改字典 ...

  6. poj 2975 Nim(博弈)

    Nim Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 5232   Accepted: 2444 Description N ...

  7. vijosP1014 旅行商简化版

    vijosP1014 旅行商简化版 链接:https://vijos.org/p/1014 [思路] 双线DP. 设ab,ab同时走.用d[i][j]表示ab所处结点i.j,且定义i>j,则有转 ...

  8. 《University Calculus》-chape5-积分法-积分的定义

    这一章节讨论积分的定义以及微积分基本定理. 笔者先前在数学证明专栏中关于高斯定理的证明的开头,给出了一段关于微积分思想的概括,文中提到根据导数(微分)的定义,根据其逆定义来给出积分的定义和计算方法,这 ...

  9. 【长篇高能】ReactiveCocoa 和 MVVM 入门

    翻译自ReactiveCocoa and MVVM, an Introduction. 文中引用的 Gist 可能无法显示.为了和谐社会, 请科学上网. MVC 任何一个正经开发过一阵子软件的人都熟悉 ...

  10. 3D视频的质量评价报告 (MSU出品)

    俄罗斯的MSU Graphics & Media Lab (Video Group)出品的3D视频的质量评价报告.测试了一些3D视频的质量,其测试方法值得我们参考.在此翻译一下部分文字. 注: ...