Skip to content

Instantly share code, notes, and snippets.

@amphineko
Last active November 26, 2019 22:41
Show Gist options
  • Save amphineko/5fde759501b7a59f5405753e25f255aa to your computer and use it in GitHub Desktop.
Save amphineko/5fde759501b7a59f5405753e25f255aa to your computer and use it in GitHub Desktop.
CancellationTokenSource.CreateLinkedTokenSource won't cancel peer tokens.
using System.Diagnostics;
var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(1));
var observer = new CancellationTokenSource();
var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, observer.Token);
await Task.Run(async () => {
try
{
await Task.Delay(TimeSpan.FromSeconds(5), linked.Token);
throw new InvalidOperationException("Operation should be cancelled before");
}
catch (OperationCanceledException)
{
Console.WriteLine($"Timeout token cancelled: {timeout.Token.IsCancellationRequested}");
Console.WriteLine($"Observer token cancelled: {observer.Token.IsCancellationRequested}");
Debug.Assert(!observer.Token.IsCancellationRequested);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment