public class TimeoutChecker
{
#region /*private member*/
long _timeout; //超时时间
System.Action<Delegate> _proc;//会超时的代码
System.Action<Delegate> _procHandle;//处理超时
System.Action<Delegate> _timeoutHandle;//超时后处理事件
System.Threading.ManualResetEvent _event = new System.Threading.ManualResetEvent(false);
#endregion
#region /*constructor method*/
/// <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();
}
};
}
#endregion
#region /*public method*/
/// <summary>
/// 等待执行
/// </summary>
/// <param name="timeout">等待时间毫秒</param>
/// <returns></returns>
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;
}
#endregion
#region private method
/// <summary>
/// 释放资源
/// </summary>
private void Dispose()
{
if (this._event != null)
this._event.Close();
this._event = null;
this._proc = null;
this._procHandle = null;
this._timeoutHandle = null;
}
#endregion
}
调用
TimeoutChecker timeout = new TimeoutChecker(
delegate
{
try
{
//把耗时的处理加到这里
}
catch (Exception he)//异常处理
{
}
},
delegate//超时处理
{
});
// 按毫秒等待
// 执行成功的处理,且未超时
if (timeout.Wait(10000))
{
Console.WriteLine("WaitTimes: {0}", DateTime.Now.ToString());
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/110454.html原文链接:https://javaforall.cn