C# Universal Code Execution Timeout Mechanism: A Complete Guide
In software development, controlling the execution time of code blocks is crucial, especially when dealing with unreliable or time-consuming external dependencies such as API calls or database queries. To do this, a common way to set timeouts for single lines of code is needed.
Implement universal timeout mechanism
The core of building a universal timeout mechanism is to terminate long-running code and intercept possible errors. For this we can adopt a layered solution:
CallWithTimeout
) that receives an operation and a timeout duration as input. This method starts code execution on a separate thread and attaches a wrapping delegate to track progress. TimeoutException
. Practical operation
The following are the specific implementation details:
<code class="language-csharp">class Program { static void Main(string[] args) { // 设置 6000 毫秒(6 秒)的超时 CallWithTimeout(FiveSecondMethod, 6000); // 设置 4000 毫秒(4 秒)的超时 CallWithTimeout(FiveSecondMethod, 4000); } static void FiveSecondMethod() { Thread.Sleep(5000); } } 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>
This implementation allows you to execute code with well-defined timeouts while providing flexibility and elegant control over execution.
The above is the detailed content of How Can I Implement a Generic Timeout Mechanism for Code Execution in C#?. For more information, please follow other related articles on the PHP Chinese website!