Implement C# Generic Timeout
我在寻找实现一种通用方法的好主意,让一行(或匿名委托)代码在超时情况下执行。
1 2 | TemperamentalClass tc = new TemperamentalClass(); tc.DoSomething(); // normally runs in 30 sec. Want to error at 1 min |
我正在寻找一种解决方案,它可以在许多地方优雅地实现,在这些地方,我的代码与喜怒无常的代码交互(我不能更改)。
此外,如果可能的话,我希望停止执行有问题的"超时"代码。
这里真正棘手的部分是通过将执行器线程从操作传递回一个可以中止的地方来终止长时间运行的任务。我使用了一个包装的委托来完成这项工作,该委托将线程传递给创建lambda的方法中的局部变量kill。
我提交这个例子,供您参考。您真正感兴趣的方法是callWithTimeout。这将通过中止长时间运行的线程并吞咽threadabortexception来取消该线程:
用途:
2执行工作的静态方法:
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 | static void CallWithTimeout(Action action, int timeoutMilliseconds) { Thread threadToKill = null; Action wrappedAction = () => { threadToKill = Thread.CurrentThread; try { action(); } catch(ThreadAbortException ex){ Thread.ResetAbort();// cancel hard aborting, lets to finish it nicely. } }; IAsyncResult result = wrappedAction.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) { wrappedAction.EndInvoke(result); } else { threadToKill.Abort(); throw new TimeoutException(); } } } |
我们在生产中大量使用这样的代码:
1 | var result = WaitFor<Result>.Run(1.Minutes(), () => service.GetSomeFragileResult()); |
实现是开放源代码的,即使在并行计算场景中也能有效地工作,并且作为lokad共享库的一部分提供
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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | /// <summary> /// Helper class for invoking tasks with timeout. Overhead is 0,005 ms. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> [Immutable] public sealed class WaitFor<TResult> { readonly TimeSpan _timeout; /// <summary> /// Initializes a new instance of the <see cref="WaitFor{T}"/> class, /// using the specified timeout for all operations. /// </summary> /// <param name="timeout">The timeout.</param> public WaitFor(TimeSpan timeout) { _timeout = timeout; } /// <summary> /// Executes the spcified function within the current thread, aborting it /// if it does not complete within the specified timeout interval. /// </summary> /// <param name="function">The function.</param> /// <returns>result of the function</returns> /// <remarks> /// The performance trick is that we do not interrupt the current /// running thread. Instead, we just create a watcher that will sleep /// until the originating thread terminates or until the timeout is /// elapsed. /// </remarks> /// <exception cref="ArgumentNullException">if function is null</exception> /// <exception cref="TimeoutException">if the function does not finish in time </exception> public TResult Run(Func<TResult> function) { if (function == null) throw new ArgumentNullException("function"); var sync = new object(); var isCompleted = false; WaitCallback watcher = obj => { var watchedThread = obj as Thread; lock (sync) { if (!isCompleted) { Monitor.Wait(sync, _timeout); } } // CAUTION: the call to Abort() can be blocking in rare situations // http://msdn.microsoft.com/en-us/library/ty8d3wta.aspx // Hence, it should not be called with the 'lock' as it could deadlock // with the 'finally' block below. if (!isCompleted) { watchedThread.Abort(); } }; try { ThreadPool.QueueUserWorkItem(watcher, Thread.CurrentThread); return function(); } catch (ThreadAbortException) { // This is our own exception. Thread.ResetAbort(); throw new TimeoutException(string.Format("The operation has timed out after {0}.", _timeout)); } finally { lock (sync) { isCompleted = true; Monitor.Pulse(sync); } } } /// <summary> /// Executes the spcified function within the current thread, aborting it /// if it does not complete within the specified timeout interval. /// </summary> /// <param name="timeout">The timeout.</param> /// <param name="function">The function.</param> /// <returns>result of the function</returns> /// <remarks> /// The performance trick is that we do not interrupt the current /// running thread. Instead, we just create a watcher that will sleep /// until the originating thread terminates or until the timeout is /// elapsed. /// </remarks> /// <exception cref="ArgumentNullException">if function is null</exception> /// <exception cref="TimeoutException">if the function does not finish in time </exception> public static TResult Run(TimeSpan timeout, Func<TResult> function) { return new WaitFor<TResult>(timeout).Run(function); } } |
此代码仍有问题,您可以尝试使用此小型测试程序:
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 | static void Main(string[] args) { // Use a sb instead of Console.WriteLine() that is modifying how synchronous object are working var sb = new StringBuilder(); for (var j = 1; j < 10; j++) // do the experiment 10 times to have chances to see the ThreadAbortException for (var ii = 8; ii < 15; ii++) { int i = ii; try { Debug.WriteLine(i); try { WaitFor<int>.Run(TimeSpan.FromMilliseconds(10), () => { Thread.Sleep(i); sb.Append("Processed" + i +" "); return i; }); } catch (TimeoutException) { sb.Append("Time out for" + i +" "); } Thread.Sleep(10); // Here to wait until we get the abort procedure } catch (ThreadAbortException) { Thread.ResetAbort(); sb.Append(" *** ThreadAbortException on" + i +" *** "); } } Console.WriteLine(sb.ToString()); } } |
有一个比赛条件。显然,在调用方法
好吧,您可以使用委托(BeginInvoke,通过回调设置一个标志-以及等待该标志或超时的原始代码)来完成操作,但问题是很难关闭正在运行的代码。例如,杀死(或暂停)线程是危险的…所以我不认为有一个简单的方法来坚定地做到这一点。
我会发布这个,但请注意,这并不理想——它不会停止长期运行的任务,也不会在失败时进行正确的清理。
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 | static void Main() { DoWork(OK, 5000); DoWork(Nasty, 5000); } static void OK() { Thread.Sleep(1000); } static void Nasty() { Thread.Sleep(10000); } static void DoWork(Action action, int timeout) { ManualResetEvent evt = new ManualResetEvent(false); AsyncCallback cb = delegate {evt.Set();}; IAsyncResult result = action.BeginInvoke(cb, null); if (evt.WaitOne(timeout)) { action.EndInvoke(result); } else { throw new TimeoutException(); } } static T DoWork<T>(Func<T> func, int timeout) { ManualResetEvent evt = new ManualResetEvent(false); AsyncCallback cb = delegate { evt.Set(); }; IAsyncResult result = func.BeginInvoke(cb, null); if (evt.WaitOne(timeout)) { return func.EndInvoke(result); } else { throw new TimeoutException(); } } |
波普·加泰林伟大答案的一些微小变化:
- func而不是action
- 对错误的超时值引发异常
- 超时时调用endinvoke
已添加重载以支持信号工作者取消执行:
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 | public static T Invoke<T> (Func<CancelEventArgs, T> function, TimeSpan timeout) { if (timeout.TotalMilliseconds <= 0) throw new ArgumentOutOfRangeException ("timeout"); CancelEventArgs args = new CancelEventArgs (false); IAsyncResult functionResult = function.BeginInvoke (args, null, null); WaitHandle waitHandle = functionResult.AsyncWaitHandle; if (!waitHandle.WaitOne (timeout)) { args.Cancel = true; // flag to worker that it should cancel! /* ?————————————————————————————————————————————————————————————————————————? | IMPORTANT: Always call EndInvoke to complete your asynchronous call. | | http://msdn.microsoft.com/en-us/library/2e08f6yc(VS.80).aspx | | (even though we arn't interested in the result) | ?————————————————————————————————————————————————————————————————————————? */ ThreadPool.UnsafeRegisterWaitForSingleObject (waitHandle, (state, timedOut) => function.EndInvoke (functionResult), null, -1, true); throw new TimeoutException (); } else return function.EndInvoke (functionResult); } public static T Invoke<T> (Func<T> function, TimeSpan timeout) { return Invoke (args => function (), timeout); // ignore CancelEventArgs } public static void Invoke (Action<CancelEventArgs> action, TimeSpan timeout) { Invoke<int> (args => { // pass a function that returns 0 & ignore result action (args); return 0; }, timeout); } public static void TryInvoke (Action action, TimeSpan timeout) { Invoke (args => action (), timeout); // ignore CancelEventArgs } |
我就是这样做的:
1 2 3 4 5 6 7 8 9 10 11 | public static class Runner { public static void Run(Action action, TimeSpan timeout) { IAsyncResult ar = action.BeginInvoke(null, null); if (ar.AsyncWaitHandle.WaitOne(timeout)) action.EndInvoke(ar); // This is necesary so that any exceptions thrown by action delegate is rethrown on completion else throw new TimeoutException("Action failed to complete using the given timeout!"); } } |
我刚刚把它敲掉了,所以它可能需要一些改进,但会做你想做的。这是一个简单的控制台应用程序,但演示了所需的原则。
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 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace TemporalThingy { class Program { static void Main(string[] args) { Action action = () => Thread.Sleep(10000); DoSomething(action, 5000); Console.ReadKey(); } static void DoSomething(Action action, int timeout) { EventWaitHandle waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset); AsyncCallback callback = ar => waitHandle.Set(); action.BeginInvoke(callback, null); if (!waitHandle.WaitOne(timeout)) throw new Exception("Failed to complete in the timeout specified."); } } } |
使用thread.join(int timeout)怎么样?
1 2 3 4 5 6 7 |