![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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(); } }
应用背景
一、网络连接,超过一定的时间链接仍未成功则取消链接,返回主线程。
二、Net框架的正则表达式有时会进入死循环,可通过超时事件来防止主线程卡死。
实例代码(网络连接)
class SourceRequest
{
private HttpWebResponse webResponse;
……//省略代码
//供外部调用的同步获取连接响应的函数
public void GetResponse(string url)
{
//创建请求对象
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//创建超时事件
TimeOutEvent timeoutEvent = new TimeOutEvent(GetResponse,30000);
//启动超时事件
timeoutEvent.Start(request);
}
//超时事件的执行线程
private void GetResponse(object request)
{
webResponse=null;
webResponse=((HttpWebRequest)request).GetResponse();
}
……//省略代码
}
实现原理