Created
June 28, 2018 13:26
-
-
Save mattiasflodin/a9675e94936ef2a7ebf3992eee560290 to your computer and use it in GitHub Desktop.
Extensions for dealing with async tasks
This file contains 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; | |
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