I'm perplex on the cancellation of several tasks and continue with a task to display result. According to what I understood, this program should display
Tasks canceled
CancellationTokenSource cts = new CancellationTokenSource();
List<Task> tasks = new List<Task>();
for(int i= 0; i<3; i++)
{
tasks.Add(Task.Run(() =>{
while(!cts.Token.IsCancellationRequested)
Thread.Sleep(500);
// Uncomment this to see 'Tasks canceled' in the result
//if(cts.Token.IsCancellationRequested)
// cts.Token.ThrowIfCancellationRequested();
},cts.Token));
}
Task.WhenAll(tasks).ContinueWith(task =>
{
if(task.IsCanceled)
Console.WriteLine("Tasks canceled");
if(task.IsCompleted)
Console.WriteLine("Tasks completed");
});
Thread.Sleep(2000);
cts.Cancel();
Unfortunately it display
Tasks completed
If i uncomment the throwing of cancel exception the program display
Tasks canceled
Tasks completed
Why? it seems that I missed something but I do not see what...