学习笔记:给某个方法设定执行超时时间
实现代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | namespace ConsoleApplication4 { public delegate void DoHandler(); public class TimeOut { private ManualResetEvent mTimeoutObject; //标记变量 private bool mBoTimeout; public DoHandler Do; public TimeOut() { // 初始状态为 停止 this .mTimeoutObject = new ManualResetEvent( true ); } ///<summary> /// 指定超时时间 异步执行某个方法 ///</summary> ///<returns>执行 是否超时</returns> public bool DoWithTimeout(TimeSpan timeSpan) { if ( this .Do == null ) { return false ; } this .mTimeoutObject.Reset(); this .mBoTimeout = true ; //标记 this .Do.BeginInvoke(DoAsyncCallBack, null ); // 等待 信号Set if (! this .mTimeoutObject.WaitOne(timeSpan, false )) { this .mBoTimeout = true ; } return this .mBoTimeout; } ///<summary> /// 异步委托 回调函数 ///</summary> ///<param name="result"></param> private void DoAsyncCallBack(IAsyncResult result) { try { this .Do.EndInvoke(result); // 指示方法的执行未超时 this .mBoTimeout = false ; } catch (Exception ex) { Console.WriteLine(ex.Message); this .mBoTimeout = true ; } finally { this .mTimeoutObject.Set(); } } } } |
测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | namespace ConsoleApplication4 { class Program { private static Stopwatch watch; private static System.Threading.Timer timer; [STAThread] static void Main( string [] args) { watch = new Stopwatch(); TimeOut timeout = new TimeOut(); timeout.Do = new Program().DoSomething; watch.Start(); timer = new System.Threading.Timer(timerCallBack, null , 0, 500); Console.WriteLine( "4秒超时开始执行" ); bool bo = timeout.DoWithTimeout( new TimeSpan(0, 0, 0, 4)); Console.WriteLine( string .Format( "4秒超时执行结果,是否超时:{0}" , bo)); Console.WriteLine( "***************************************************" ); timeout = new TimeOut(); timeout.Do = new Program().DoSomething; Console.WriteLine( "6秒超时开始执行" ); bo = timeout.DoWithTimeout( new TimeSpan(0, 0, 0, 6)); Console.WriteLine( string .Format( "6秒超时执行结果,是否超时:{0}" , bo)); timerCallBack( null ); watch.Stop(); timer.Dispose(); Console.ReadLine(); } static void timerCallBack( object obj) { Console.WriteLine( string .Format( "运行时间:{0}秒" , watch.Elapsed.TotalSeconds.ToString( "F2" ))); } public void DoSomething() { // 休眠 5秒 System.Threading.Thread.Sleep( new TimeSpan(0, 0, 0, 5)); } } } |
执行结果:
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步