Implementing a universal timeout mechanism in C#
When interacting with unreliable code, it is crucial to implement a common mechanism to execute specific blocks of code with defined timeouts. This general approach can be applied to various scenarios and enhances the robustness of the code.
One of the main challenges is how to terminate long-running tasks if they time out. To overcome this problem, we use a wrapped delegate. This delegate passes the thread of execution to a local variable, allowing the thread to be terminated if necessary.
The provided C# code contains a static method CallWithTimeout
that performs a specified operation within a specified timeout. If it times out, this method will abort the running thread and throw a TimeoutException
exception.
Example usage:
<code class="language-csharp">class Program { static void Main(string[] args) { // 五秒钟的方法,超时时间为六秒钟 CallWithTimeout(FiveSecondMethod, 6000); } static void FiveSecondMethod() { Thread.Sleep(5000); } }</code>
This code demonstrates how to implement a universal timeout mechanism in C#, allowing developers to handle time-consuming tasks gracefully and prevent code from getting stuck during execution.
The above is the detailed content of How to Implement Generic Timeouts in C# to Prevent Code from Hanging?. For more information, please follow other related articles on the PHP Chinese website!