Skip to content

Instantly share code, notes, and snippets.

@rdavisau
Created April 17, 2015 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdavisau/a3bfa15fc77fbc789c59 to your computer and use it in GitHub Desktop.
Save rdavisau/a3bfa15fc77fbc789c59 to your computer and use it in GitHub Desktop.
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;
else
{
if (cancellationTokenSource != null)
cancellationTokenSource.Cancel();
throw new TimeoutException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment