Skip to content

Instantly share code, notes, and snippets.

@noseratio
Last active August 29, 2015 14:25
Show Gist options
  • Save noseratio/2145d69edce633d76e7b to your computer and use it in GitHub Desktop.
Save noseratio/2145d69edce633d76e7b to your computer and use it in GitHub Desktop.
// http://stackoverflow.com/q/31495411/1768303
// use: await Task.Delay(5000, token.CreateAsynCancellationToken());
public static CancellationToken CreateAsynCancellationToken(this CancellationToken @this)
{
var cts = new CancellationTokenSource();
var reg = default(CancellationTokenRegistration);
reg = @this.Register(() =>
{
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
cts.Cancel();
}
finally
{
reg.Dispose();
}
});
}, useSynchronizationContext: false);
return cts.Token;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment