Created
April 17, 2015 00:30
-
-
Save rdavisau/a3bfa15fc77fbc789c59 to your computer and use it in GitHub Desktop.
Timeout extension method for Task<T>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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