Created
June 1, 2019 09:28
-
-
Save aliabidzaidi/ee477c6e2e97bd96218c4242f62336c4 to your computer and use it in GitHub Desktop.
Cancelling multiple tasks together by using a composite cancellation source
This file contains 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
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