/// <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. Scarborough Fair 绝美天籁

    很少见的男声唱法,而且还古色古香: https://www.youtube.com/watch?v=sgbo2QWLBzI https://www.youtube.com/watch?v=-BakWV ...

  2. lua中求table长度

    关于lua table介绍,看以前的文章http://www.cnblogs.com/youxin/p/3672467.html. 官方文档是这么描述#的: 取长度操作符写作一元操作 #. 字符串的长 ...

  3. 创办支持多种屏幕尺寸的Android应用

    创建支持多种屏幕尺寸的Android应用 Android涉及各种各样的支持不同屏幕尺寸和密度的设备.对于应用程序,Android系统通过设备和句柄提供了统一的开发环境,大部分工作是校正每一个应用程序的 ...

  4. 纯css切换左侧菜单

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  5. Linux Shell编程(28)——进程替换

    进程替换与命令替换很相似. 命令替换把一个命令的结果赋给一个变量,例如 dir_contents=`ls -al`或xref=$. 进程替换则是把一个进程的输出回馈给另一个进程 (换句话说,它把一个命 ...

  6. 【转】android官方侧滑菜单DrawerLayout详解

    原文网址:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/0925/1713.html drawerLayout是Support ...

  7. MyEclipse中导入Spring 4.0源码

    http://www.cnblogs.com/shi-blog/p/4132183.html

  8. Python IDLE 清屏工具

     转载自:http://www.cnblogs.com/maybego/p/3234055.html   1.下载clearwindow.py(右击-目标另存为,直接点击会打开脚本内容). 2.拷贝c ...

  9. 用xib文件,配置UITableViewCell

    http://www.cnblogs.com/lixingle/p/3287499.html 在运行时候,如果出现“this class is not key value coding-complia ...

  10. 修改maven中的jdk版本

    1.修改项目的pom.xml文件 <build> <plugins> <plugin> <groupId>org.apache.maven.plugin ...