/// <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. rm加转义很危险

    rm -r 想转义一个空格字符,转得不对 -r, -R, --recursive 递归删除目录及其内容 连续rm了n个不想rm的文件夹.%>_<% 想起来以前有人也因为rm的失误把整个wo ...

  2. 【POJ1284】Primitive Roots 欧拉函数

    题目描述: 题意: 定义原根:对于一个整数x,0<x<p,是一个mod p下的原根,当且仅当集合{ (xi mod p) | 1 <= i <= p-1 } 等于{ 1, .. ...

  3. VLD(Visual LeakDetector)内存泄露库的使用

    VLD简介 由于C/C++语言没有所谓的垃圾收集器,内存的分配和释放都需要程序员自己来控制,这会给C/C++程序员带来一定的困难.当您的程序越来越复杂时,它的内存管理也会变得越来越困难.内存泄漏.内存 ...

  4. QPainter类学习

    详细描述: QPainter类提供了许多高度优化的函数去做大部分的GUI绘制工作.它可以画从简单的线到复杂的形状.通常情况下,QPainter的使用是在widget当中的painter事件使用.记得在 ...

  5. vsftp被动模式启用iptables访问设置

    vsftpd服务搭建好之后,如果是使用主动模式访问.那么启用iptables只需添加以下规则即可: -A RH-Firewall-1-INPUT -m state --state NEW -m tcp ...

  6. 一步一步自定义SpringMVC参数解析器

    随心所欲,自定义参数解析器绑定数据. 题图:from Zoommy 干货 SpringMVC解析器用于解析request请求参数并绑定数据到Controller的入参上. 自定义一个参数解析器需要实现 ...

  7. BZOJ3039: 玉蟾宫&wikioi2491 玉蟾宫

    3039: 玉蟾宫 Time Limit: 2 Sec  Memory Limit: 128 MBSubmit: 430  Solved: 265[Submit][Status] Descriptio ...

  8. c语言 快速排序---归并排序----堆排序

    //快速排序: #include <stdio.h> #define MAX 500000 int s[MAX]; void Q_Sort(int start,int end) { int ...

  9. HDU 1230 火星A+B

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1230 水题模拟一道,主要考验代码能力,刷完题就感觉自己还是太弱了. #include<cmath ...

  10. 实现自己的脚本语言ngscript之三:语法设计

    这是第四篇了,之所以隔了这么久才写,一方面是因为最近开始实习了,另一方面是因为设计语法真是要考虑很多东西. 于是我去读了这本书,里面实现了两种语言,一种跟js差不多语法,用ast解释执行:另一种语法类 ...