I have a button thats spawns 4 tasks. The same button changes to a cancel button and clicking this should cancel all 4 tasks. Should I pass the same cancel token to all 4 tasks and have them poll on the same token for IsCancelRequested ? I am confused after reading the msdn doc on createlinkedtokensource. How is this normally done ? thank you
Update: Task.WaitAll() waits tills all tasks complete execution. Similarly how to know when all tasks have been canceled once the shared cancel token source is set to cancel.
Yeah, what you said about using a single
CancellationTokenis correct. You can create a singleCancellationTokenSourceand use itsCancellationTokenfor all of the tasks. Your tasks should check the token regularly for cancellation.For example:
Your button can call
cts.Cancel();to cancel the tasks.Update for question update:
There are a few ways to do what you ask. One way is to use
ct.IsCancellationRequestedto check cancellation without throwing, then allow your task to complete. ThenTask.WaitAll(tasks)will complete when all of the tasks have been cancelled.I’ve updated the code to reflect that change.