Skip to content

Instantly share code, notes, and snippets.

@jcmm33
Created May 15, 2015 08:45
Show Gist options
  • Save jcmm33/6c4cbc3f942b034ae429 to your computer and use it in GitHub Desktop.
Save jcmm33/6c4cbc3f942b034ae429 to your computer and use it in GitHub Desktop.
Task Cancellation Extension
/// <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