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

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

Susan Sarandon
Susan SarandonOriginal
2025-01-23 12:21:10883browse

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

Implementing a universal timeout mechanism in C#

A common need in programming is to be able to execute code with a specified timeout. This becomes critical when dealing with external systems or code that may take too long to complete. Implementing a common timeout mechanism allows for consistent behavior across the entire code base, ensuring that unresponsive code is handled in an appropriate manner.

In this case, the goal is to create a generic method that can execute any given code within a specified timeout. The solution should gracefully handle situations where the code exceeds the timeout and provide a mechanism to stop its execution.

An elegant way to achieve this is to use delegates. The following code snippet demonstrates a generic timeout method named CallWithTimeout that accepts an Action delegate and a timeout value in milliseconds:

<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>

In this method, a separate thread is created to perform the given operation. The key to controlling execution is to use a wrapping delegate that captures a reference to the thread. If the operation exceeds the timeout, the thread is gracefully terminated and a TimeoutException is thrown.

By using this universal timeout mechanism, developers can easily protect their code from unresponsive external systems or blocks of code. It promotes robust application behavior and enhances handling of potential exceptions.

The above is the detailed content of How Can I Implement a Generic Timeout Mechanism in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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