Skip to content

Instantly share code, notes, and snippets.

@aliabidzaidi
Created June 1, 2019 09:28
Show Gist options
  • Save aliabidzaidi/ee477c6e2e97bd96218c4242f62336c4 to your computer and use it in GitHub Desktop.
Save aliabidzaidi/ee477c6e2e97bd96218c4242f62336c4 to your computer and use it in GitHub Desktop.
Cancelling multiple tasks together by using a composite cancellation source
CancellationTokenSource source1 = new CancellationTokenSource();
CancellationTokenSource source2 = new CancellationTokenSource();
CancellationTokenSource source3 = new CancellationTokenSource();
//Composite Cancellation Source example
CancellationTokenSource compositeSource = CancellationTokenSource.CreateLinkedTokenSource(source1.Token, source2.Token, source3.Token);
//Create 3 tasks and pass token sources to different tasks and call each Start methods
//Monitor multiple task cancellation
Task waitHandleTask = new Task(() =>
{
Console.WriteLine("Waiting for task to be cancelled.........(Press any key)");
compositeSource.Token.WaitHandle.WaitOne();
Console.WriteLine("Task Cancelled");
}, compositeSource.Token);
waitHandleTask.Start();
Console.ReadKey();
//Cancel any token source
source3.Cancel();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment