Home > Backend Development > C++ > How Can I Implement a Generic Timeout Mechanism for Code Execution in C#?

How Can I Implement a Generic Timeout Mechanism for Code Execution in C#?

Susan Sarandon
Release: 2025-01-23 12:01:12
Original
982 people have browsed it

How Can I Implement a Generic Timeout Mechanism for Code Execution in C#?

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:

  • Wrapped Delegate: Creates a delegate that captures the target code and provides access to the thread handle.
  • Timeout Execution Method: Creates a method (such as 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.
  • Thread Termination: Upon timeout, terminate the thread responsible for long-running code and throw 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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template