Timeouts in C#
Timeouts are important for programs that connect to external resources or that otherwise need to bound execution time. Implementing timeouts in C# is straightforward using the Task
class and its WaitAsync
method.
Running this program shows the first operation timing out and the second succeeding.
In this C# version, we use Task.Run
to simulate long-running operations. The Task.Delay
method is used to create a delay, similar to time.Sleep
in the original example.
We implement timeouts using the Task.WaitAsync
method, which allows us to specify a timeout duration. If the task doesn’t complete within the specified time, a TimeoutException
is thrown.
The try-catch
blocks are used to handle the timeout scenarios. If a TimeoutException
is caught, we print the timeout message. Otherwise, the task completed successfully, and we print the result.
This approach provides a clean and idiomatic way to implement timeouts in C#, leveraging the language’s built-in asynchronous programming features.