C # timeout tool Version 2,
Source code is provided, and no test demo is provided.
/// <Summary> /// timeout tool /// </summary> public class TimeoutTools {private Timer timer; /// <summary> // whether the event is being executed // </summary> private bool EventRunning {get; set ;} /// <summary> /// location /// </summary> private uint Position {get; set ;} /// <summary> /// timeout // </summary> public event EventHandler TimeoutEvent; /// <summary> /// step value /// <para> default value: 1 </para> /// </summary> public uint StepLength {Get; set ;} /// <summary> /// timeout length /// <para> default 180 </para> /// </summary> public uint TimeoutLength {get; set ;} /// <summary> /// default constructor /// </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. setTimerPara M (0, 1000 );} /// <summary> /// specify the timeout time to execute a method // </summary> /// <returns> whether the execution times out </returns> public static bool DoAction (timeSpan timeSpan, action action) {if (action = null) throw new ArgumentNullException ("action is null"); bool timeout = true; try {// call Action IAsyncResult result = action asynchronously. beginInvoke (null, null); // Wait if (result. asyncWaitHandle. waitOne (timeSpan, false) {timeout = false ;} If (! Timeout) {action. endInvoke (result) ;}} catch (Exception) {timeout = true;} return timeout ;} /// <summary> /// set the timer parameter /// </summary> /// <param name = "dueTime"> default value of millisecond 0 </param> /// <param name = "period"> default value of millisecond: 1000 </param> public void SetTimerParam (int dueTime, int period) {this. timer. change (dueTime, period);} // <summary> // receives the signal // </summary> public void Reset () {this. position = 0;} prot Ected void OnTimeOut () {if (this. EventRunning) {return;} this. EventRunning = true; if (this. TimeoutEvent! = Null) {this. TimeoutEvent (this, EventArgs. Empty);} this. EventRunning = false ;}}