The brief answer is you can cancel the waiting tasks via corresponding CancellationToken built by CancellationTokenSource. Here is an example.
var tokenSource = new CancellationTokenSource(); var task = Task.Factory.StartNew(() => { for (int i = 0; i < 10; i++) { if (tokenSource.IsCancellationRequested) { //you know the task is cancelled //do something to stop the task //or you can use tokenSource.Token.ThrowIfCancellationRequested() //to control the flow } else { //working on step i } } }, tokenSource.Token); try { task.Wait(tokenSource.Token); } catch (OperationCanceledException cancelEx) { //roll back or something } //somewhere e.g. a cancel button click event you call tokenSource.Cancel()
Things are a little different when you are dealing with a few tasks. Firstly you need to know when cancelling a task, will other tasks continue? If yes, you need to create different cancellation tokens for different tasks and handle the cancellation independently. Otherwise they can share the same cancellation token. Different requirement causes different cancellation handling policy.