Skip to content

Instantly share code, notes, and snippets.

@keimpema
Created October 16, 2017 14:05
Show Gist options
  • Save keimpema/ae8450ca5794db421adf58deb23fc511 to your computer and use it in GitHub Desktop.
Save keimpema/ae8450ca5794db421adf58deb23fc511 to your computer and use it in GitHub Desktop.
TaskExtensions
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