线程运行超时处理类
2012-03-14 14:05
225 查看
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()); }
相关文章推荐
- JAVA线程的超时处理
- Nucleus PLUS的启动、运行线程和中断处理
- 线程池中的某个线程一直运行中, 某个 update sql 执行超时
- CLR 无法从 COM 上下文 0x1a2740 转换为 COM 上下文 0x1a28b0,这种状态已持续 60 秒。拥有目标上下文/单元的线程很有可能执行的是非泵式等待或者在不发送 Windows 消息的情况下处理一个运行时间非常长的操作
- java线程超时处理
- MHA复制检测时提示slave IO线程没有运行的处理过程
- 不允许启动新事务,因为有其他线程正在该会话中运行(ef并发错误处理之一)
- vb.net shell线程执行完成后再运行以后处理 函数
- JAVA多线程——线程运行时异常的处理
- 掌握GCD以及后台永久运行的代码 (使用GCD处理后台线程和UI线程的交互)
- Android 中线程网络超时的处理
- JAVA处理线程超时
- UNIX/LINUX 单线程I/O 超时处理
- 【故障处理141119】一次数据库不繁忙时一条sql语句2个运行计划导致业务超时的故障处理
- 《CLR via C#》之线程处理——协作式取消和超时
- 【转】JAVA处理线程超时
- JAVA处理线程超时
- 程序运行超时处理——JAVA
- JAVA处理线程超时
- 在MFC 子线程中使用UI(控件)退出时死锁或者超时处理参考