记录一下怕要用时忘记
直接上代码
/// <summary>
/// 超时处理
/// </summary>
public class TimeoutChecker
{
long _timeout; //超时时间
System.Action<Delegate> _proc; //会超时的代码
System.Action<Delegate> _procHandle; //处理超时
System.Action<Delegate> _timeoutHandle; //超时后处理事件
System.Threading.ManualResetEvent _event = new System.Threading.ManualResetEvent(false);
/// <summary>
/// 超时处理
/// </summary>
/// <param name="proc"></param>
/// <param name="timeoutHandle"></param>
public TimeoutChecker(System.Action<Delegate> proc, System.Action<Delegate> timeoutHandle)
{
this._proc = proc;
this._timeoutHandle = timeoutHandle;
this._procHandle = delegate
{
//计算代码执行的时间
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
if (this._proc != null)
this._proc(null);
sw.Stop();
//如果执行时间小于超时时间则通知用户线程
if (sw.ElapsedMilliseconds < this._timeout && this._event != null)
{
this._event.Set();
}
};
}
public bool Wait(long timeout)
{
this._timeout = timeout;
//异步执行
this._procHandle.BeginInvoke(null, null, null);
//如果在规定时间内没等到通知则为 false
bool flag = this._event.WaitOne((int)timeout, false);
if (!flag)
{
//触发超时时间
if (this._timeoutHandle != null)
this._timeoutHandle(null);
}
this.Dispose();
return flag;
}
private void Dispose()
{
if (this._event != null)
this._event.Close();
this._event = null;
this._proc = null;
this._procHandle = null;
this._timeoutHandle = null;
}
}
实现流程
TimeoutChecker timeout = new TimeoutChecker(
delegate
{
//要运行的函数
},
delegate
{
//超时处理位置
});
if (timeout.Wait(5000))
{
//正常
}
本文作者:[博主]大顺
本文链接:https://shunnet.top/qumQBj
版权声明:转载注明出处,谢谢 ☺
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有