WaitAsync
11/21/2021
.NET 6 has a new method added to System.Threading.Tasks.Task
to wait for a task completion or timeout. WaitAsync
method completes with the result of the task it is invoked on, or throws a timeout exception when the given timeout reached or throws a TaskCancelledException
if the given cancellation token is set to cancelled state.
The method's primary use-case is to add cancellation or timeout ability for async methods, that inherently don't provide such capability. One use-case could be unit tests, where we explicitly want to time out and fail a test if the method invoked as the system under test is an async operation without a timeout overload. This way we can let other tests to be executed in the test suite.
Previously a poor man (woman)'s implementation for such timeout could look as:
public static async Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout) { if (task.IsCompleted) return await task; var cts = new CancellationTokenSource(); if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token))) { cts.Cancel(); return await task; } else { throw new TimeoutException(); } }