Skip to content

Instantly share code, notes, and snippets.

@crozone
Created April 22, 2021 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crozone/61f4f5fde8e7de8c3ad65543195f5212 to your computer and use it in GitHub Desktop.
Save crozone/61f4f5fde8e7de8c3ad65543195f5212 to your computer and use it in GitHub Desktop.
CancellationToken.WhenCancelled()
using System.Threading;
using System.Threading.Tasks;
public static class CancellationTokenExtensions
{
public static async Task WhenCancelled(this CancellationToken cancellationToken)
{
TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() =>
{
taskCompletionSource.TrySetResult(true);
}))
{
await taskCompletionSource.Task;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment