附源码,没有附测试demo
之前的工具类:
////// 超时工具 /// public class TimeoutTools : IDisposable { private System.Windows.Forms.Timer timer; ////// 位置 /// public uint Position { get; private set; } ////// 超时事件 /// public event EventHandler TimeoutEvent; ////// Tick事件 /// public event EventHandler TickEvent; ////// 步长值 /// public uint StepLength { get; set; } ///默认值1 ////// 超时长度 /// public uint TimeoutLength { get; set; } ///默认180 ////// 默认构造函数 /// public TimeoutTools(System.ComponentModel.IContainer container) { this.StepLength = 1; this.TimeoutLength = 180; this.timer = new System.Windows.Forms.Timer(container); this.timer.Interval = 1000; this.timer.Enabled = false; timer.Tick += (sender, e) => { this.Position += this.StepLength; if (this.Position >= this.TimeoutLength) { this.Reset(); this.OnTimeOut(); } else { if (this.TickEvent != null) { this.TickEvent(this, EventArgs.Empty); } } }; } ////// 指定超时时间 执行某个方法 /// ///执行 是否超时 public static bool DoAction(TimeSpan timeSpan, Action action) { if (action == null) throw new ArgumentNullException("action is null"); bool timeout = true; try { // 异步调用Action IAsyncResult result = action.BeginInvoke(null, null); // Wait if (result.AsyncWaitHandle.WaitOne(timeSpan, false)) { timeout = false; } if (!timeout) { action.EndInvoke(result); } } catch (Exception) { timeout = true; } return timeout; } ////// 设置计时器参数 /// /// 毫秒 public void SetInterval(int period) { if (period == Timeout.Infinite) { this.timer.Enabled = false; return; } this.timer.Interval = period; this.timer.Enabled = true; } ////// 接收到信号 /// public void Reset() { this.Position = 0; } protected void OnTimeOut() { if (this.TimeoutEvent != null) { this.TimeoutEvent(this, EventArgs.Empty); } } public void Dispose() { if (this.timer == null) return; this.timer.Enabled = false; this.timer.Dispose(); } }