Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Timeout extension method for Task<T>
// I don't remember where this is taken/adapted from.
public static class AsyncExtensions
public static async Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout, CancellationTokenSource cancellationTokenSource = null)
if (task == await Task.WhenAny(task, Task.Delay(timeout)))
return await task;
if (cancellationTokenSource != null)
throw new TimeoutException();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment