附源码,没有附测试demo
/// <summary> /// 超时工具 /// </summary> public class TimeoutTools { private Timer timer; /// <summary> /// 事件是否正在执行 /// </summary> private bool EventRunning { get; set; } /// <summary> /// 位置 /// </summary> private uint Position { get; set; } /// <summary> /// 超时事情 /// </summary> public event EventHandler TimeoutEvent; /// <summary> /// 步长值 /// <para>默认值1</para> /// </summary> public uint StepLength { get; set; } /// <summary> /// 超时长度 /// <para>默认180</para> /// </summary> public uint TimeoutLength { get; set; } /// <summary> /// 默认构造函数 /// </summary> public TimeoutTools() { this.StepLength = 1; this.TimeoutLength = 180; this.timer = new Timer((obj) => { this.Position += this.StepLength; if (this.Position >= this.TimeoutLength) { this.Reset(); this.OnTimeOut(); } }); // 一秒一次 this.SetTimerParam(0, 1000); } ///<summary> /// 指定超时时间 执行某个方法 ///</summary> ///<returns>执行 是否超时</returns> 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; } /// <summary> /// 设置计时器参数 /// </summary> /// <param name="dueTime">毫秒 默认值0</param> /// <param name="period">毫秒 默认值1000</param> public void SetTimerParam(int dueTime, int period) { this.timer.Change(dueTime, period); } /// <summary> /// 接收到信号 /// </summary> public void Reset() { this.Position = 0; } protected void OnTimeOut() { if (this.EventRunning) { return; } this.EventRunning = true; if (this.TimeoutEvent != null) { this.TimeoutEvent(this, EventArgs.Empty); } this.EventRunning = false; } }