Skip to content

Instantly share code, notes, and snippets.

@mattiasflodin
Created June 28, 2018 13:26
Show Gist options
  • Save mattiasflodin/a9675e94936ef2a7ebf3992eee560290 to your computer and use it in GitHub Desktop.
Save mattiasflodin/a9675e94936ef2a7ebf3992eee560290 to your computer and use it in GitHub Desktop.
Extensions for dealing with async tasks
using System;
using System.Threading;
using System.Threading.Tasks;
public static class TaskExtensions
{
// Forward result of task if it completes before given timeout. Otherwise,
// return default(T). The original task will remain running until it completes.
public static async Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout)
{
var cts = new CancellationTokenSource(timeout);
try
{
return await task.ContinueWith(completedTask => completedTask.GetAwaiter().GetResult(),
cts.Token,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
catch (OperationCanceledException)
{
if (cts.IsCancellationRequested)
{
return default(T);
}
else
{
throw;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment