Created
May 15, 2015 08:45
-
-
Save jcmm33/6c4cbc3f942b034ae429 to your computer and use it in GitHub Desktop.
Task Cancellation Extension
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
/// <summary> | |
/// Task Extensions | |
/// </summary> | |
public static class TaskExtensions | |
{ | |
/// <summary> | |
/// Enable cancellation for a task for which cancellation tokens can't be specified. | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="task"></param> | |
/// <param name="cancellationToken"></param> | |
/// <returns></returns> | |
public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken) | |
{ | |
var tcs = new TaskCompletionSource<bool>(); | |
using (cancellationToken.Register( | |
s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs)) | |
if (task != await Task.WhenAny(task, tcs.Task)) | |
throw new OperationCanceledException(cancellationToken); | |
return await task; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment