C#超时工具类第二版

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: |||超大  

附源码,没有附测试demo

之前的工具类:C# 给某个方法设定执行超时时间

///<summary>///超时工具///</summary>publicclassTimeoutTools : IDisposable

{PRivateSystem.Windows.Forms.Timer timer;///<summary>///位置///</summary>publicuintPosition {get;privateset; }///<summary>///超时事件///</summary>publiceventEventHandler TimeoutEvent;///<summary>///Tick事件///</summary>publiceventEventHandler TickEvent;///<summary>///步长值///<para>默认值1</para>///</summary>publicuintStepLength {get;set; }///<summary>///超时长度///<para>默认180</para>///</summary>publicuintTimeoutLength {get;set; }///<summary>///默认构造函数///</summary>publicTimeoutTools(System.ComponentModel.IContainer container)

{this.StepLength =1;this.TimeoutLength =180;this.timer =newSystem.Windows.Forms.Timer(container);this.timer.Interval =1000;this.timer.Enabled =false;

timer.Tick+= (sender, e) =>{this.Position +=this.StepLength;if(this.Position >=this.TimeoutLength)

{this.Reset();this.OnTimeOut();

}else{if(this.TickEvent !=null)

{this.TickEvent(this, EventArgs.Empty);

}

}

};

}///<summary>///指定超时时间 执行某个方法///</summary>///<returns>执行 是否超时</returns>publicstaticboolDoAction(TimeSpan timeSpan, Action action)

{if(action ==null)thrownewArgumentNullException("action is null");booltimeout =true;try{//异步调用ActionIAsyncResult result = action.BeginInvoke(null,null);//Waitif(result.AsyncWaitHandle.WaitOne(timeSpan,false))

{

timeout=false;

}if(!timeout)

{

action.EndInvoke(result);

}

}catch(Exception)

{

timeout=true;

}returntimeout;

}///<summary>///设置计时器参数///</summary>///<param name="period">毫秒</param>publicvoidSetInterval(intperiod)

{if(period ==Timeout.Infinite)

{this.timer.Enabled =false;return;

}this.timer.Interval =period;this.timer.Enabled =true;

}///<summary>///接收到信号///</summary>publicvoidReset()

{this.Position =0;

}protectedvoidOnTimeOut()

{if(this.TimeoutEvent !=null)

{this.TimeoutEvent(this, EventArgs.Empty);

}

}publicvoidDispose()

{if(this.timer ==null)return;this.timer.Enabled =false;this.timer.Dispose();

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航