Public class timeoutchecker {# region/* Private member */long _ timeout; // timeout time system. action <delegate> _ proc; // code system that times out. action <delegate> _ prochandle; // processing timeout system. action <delegate> _ timeouthandle; // System of the event after timeout. threading. manualresetevent _ event = new system. threading. manualresetevent (false ); # endregion # region/* constructor Method * // <summary> // The method of Structure Selection /// </Summary> // <Param name = "proc"> Code that will time out </param> // <Param name = "timeouthandle"> post-Timeout event </param> Public timeoutchecker (system. action <delegate> proc, system. action <delegate> timeouthandle) {This. _ proc = proc; this. _ timeouthandle = timeouthandle; this. _ prochandle = delegate {// calculate the code execution time system. diagnostics. stopwatch Sw = new system. diagnostics. stopwatch (); Sw. start (); If (this. _ proc! = NULL) This. _ proc (null); Sw. stop (); // if the execution time is earlier than the timeout time, the user thread if (SW. elapsedmilliseconds <this. _ timeout & this. _ event! = NULL) {This. _ event. set ();}};} # endregion # region/* Public Method * // <summary> // wait for execution /// </Summary> /// <Param name = "timeout"> wait time in milliseconds </param> /// <returns> </returns> Public bool wait (long timeout) {This. _ timeout = timeout; // asynchronous execution of this. _ prochandle. begininvoke (null, null, null); // false bool flag = this if the notification is not received within the specified time. _ event. waitone (INT) Timeout, false); If (! Flag) {// trigger timeout if (this. _ timeouthandle! = NULL) This. _ timeouthandle (null);} This. dispose (); Return flag;} # endregion # region private method // <summary> // release resources /// </Summary> private void dispose () {If (this. _ event! = NULL) This. _ event. close (); this. _ event = NULL; this. _ proc = NULL; this. _ prochandle = NULL; this. _ timeouthandle = NULL;} # endregion}
Call
Timeoutchecker timeout = new timeoutchecker (delegate {try {// Add time-consuming processing here} catch (exception he) // Exception Handling {}}, delegate // timeout processing {}); // wait for processing in milliseconds // The execution is successful, and if (timeout. wait (10000) {console. writeline ("waittimes: {0}", datetime. now. tostring ());}