Question:
How to create a generic method in C# that executes a single line of code within a given timeout? This is useful for working with code that cannot be modified and may cause problems, and to terminate code execution on a timeout.
Answer:
Implementing a generic timeout handler requires careful consideration, especially in terms of stopping problematic code after a timeout. The following solution combines lambda expressions and threading.
The key method is CallWithTimeout
which accepts the code to execute (a Action
delegate) and the desired timeout in milliseconds.
Implementation:
<code class="language-csharp"> static void CallWithTimeout(Action action, int timeoutMilliseconds) { Thread threadToKill = null; Action wrappedAction = () => { threadToKill = Thread.CurrentThread; try { action(); } catch (ThreadAbortException ex) { Thread.ResetAbort(); // 取消强制中止以实现优雅退出。 } }; IAsyncResult result = wrappedAction.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) { wrappedAction.EndInvoke(result); } else { threadToKill.Abort(); throw new TimeoutException(); } }</code>
Usage:
TheCallWithTimeout
method can be used as follows:
<code class="language-csharp"> static void Main(string[] args) { // 调用一个执行时间为5秒的方法,设置6秒的超时时间 CallWithTimeout(FiveSecondMethod, 6000); // 调用同一个方法,设置4秒的超时时间,这将触发超时异常 CallWithTimeout(FiveSecondMethod, 4000); } static void FiveSecondMethod() { Thread.Sleep(5000); }</code>
In this example, FiveSecondMethod
will run successfully within the 6 second timeout, but will throw a TimeoutException
exception within the 4 second timeout.
Note:
The above code cancels the timeout thread by aborting the thread, which may not be ideal in some cases. If a more elegant cancellation method is required, other mechanisms can be implemented.
The above is the detailed content of How Can I Implement a Generic Timeout for a Single Line of Code in C#?. For more information, please follow other related articles on the PHP Chinese website!