Created
October 16, 2017 14:05
-
-
Save keimpema/ae8450ca5794db421adf58deb23fc511 to your computer and use it in GitHub Desktop.
TaskExtensions
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
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace Usenet.Extensions | |
{ | |
public static class TaskExtensions | |
{ | |
public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout) | |
{ | |
using (var timeoutCancellationTokenSource = new CancellationTokenSource()) | |
{ | |
Task completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token)); | |
if (completedTask != task) | |
{ | |
throw new TimeoutException("The operation has timed out."); | |
} | |
timeoutCancellationTokenSource.Cancel(); | |
return await task; // Very important in order to propagate exceptions | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment