View code
public class TimeOutEvent { public delegate void TimeOutStart(object o); private TimeOutStart timeOutStart; private Thread regexThread; private System.Timers.Timer regexTimeoutTimer; private ManualResetEvent allDone; public TimeOutEvent(TimeOutStart startAddress,int time=1000) { timeOutStart = startAddress; regexThread = null; regexTimeoutTimer = new System.Timers.Timer(); regexTimeoutTimer.Interval = time; regexTimeoutTimer.AutoReset = false; regexTimeoutTimer.Elapsed += new ElapsedEventHandler(regexTimeoutTimer_Elapsed); allDone = new ManualResetEvent(false); } public bool Start(object o) { if (timeOutStart == null) return false; allDone.Reset(); regexThread = new Thread(new ParameterizedThreadStart(Execute)); regexThread.Start(o); regexTimeoutTimer.Start(); allDone.WaitOne(); regexTimeoutTimer.Stop(); return true; } private void Execute(object o) { if (timeOutStart != null) timeOutStart(o); allDone.Set(); } void regexTimeoutTimer_Elapsed(object sender, ElapsedEventArgs e) { if (regexThread!=null && regexThread.ThreadState == ThreadState.Running) { regexThread.Abort(); } allDone.Set(); } }
Application background
1. network connection. If the connection fails after a certain period of time, the connection is canceled and the main thread is returned.
Ii. Regular Expressions in the Net Framework sometimes enter an endless loop. Timeout events can be used to prevent the master thread from getting stuck.
Instance code (network connection)
Class sourcerequest {private httpwebresponse webresponse ;...... // Omitting code // synchronously obtain the connection response function for external calls
Public void getresponse (string URL) {// create a request object
Httpwebrequest request = (httpwebrequest) webrequest. Create (URL); // create a timeout event
Timeoutevent = new timeoutevent (getresponse, 30000); // start the timeout event
Timeoutevent. Start (request);} // execution thread of the timeout event
Private void getresponse (Object Request) {webresponse = NULL; webresponse = (httpwebrequest) request). getresponse ();}...... // Omitting code}
Implementation Principle