Created
April 24, 2018 20:12
-
-
Save skarllot/583da436e8c1a659da276c274c0cdfc0 to your computer and use it in GitHub Desktop.
Enable await for CancellationToken
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
using System; | |
using System.Runtime.CompilerServices; | |
using System.Threading; | |
public static class CancellationTokenAsynchronousExtensions | |
{ | |
public static CancellationTokenAwaiter GetAwaiter(this CancellationToken cancellationToken) | |
{ | |
return new CancellationTokenAwaiter(cancellationToken); | |
} | |
public struct CancellationTokenAwaiter : INotifyCompletion | |
{ | |
private readonly CancellationToken cancellationToken; | |
public CancellationTokenAwaiter(CancellationToken cancellationToken) | |
{ | |
this.cancellationToken = cancellationToken; | |
} | |
public bool IsCompleted => cancellationToken.IsCancellationRequested; | |
public void OnCompleted(Action continuation) => cancellationToken.Register(continuation); | |
public void GetResult() | |
{ | |
if (cancellationToken.IsCancellationRequested) | |
return; | |
using (var evt = new ManualResetEventSlim()) | |
evt.Wait(cancellationToken); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment