Hi @rajesh yadav , Since others have given great insights, I will offer what I've found regarding this subject.
The two messages depend entirely on which task reaches a terminal state first and whether the cancellation token actually interrupts the download.
- "Download task has been cancelled."
You pressed Enter before all the downloads finished, and the cancellation token stopped the work mid-way. A download was still in progress when the cancel request hit, so
sumPageSizesTask
threw aTaskCanceledException
and ended in the Canceled state. - "Download task completed before cancel request was processed." You pressed Enter before all the downloads finished, but they were so close to completion that the task finished normally before the cancellation token took effect. This case is rare, because most of the time the HTTP calls will observe the cancellation and throw before completing.
Though through testing, I've found that sumPageSizesTask always complete before cancelTask, therefore finishedTask gets the value of sumPageSizesTask:
Task finishedTask = await Task.WhenAny(new[] { cancelTask, sumPageSizesTask });
Thus, this part is probably going to get skipped over:
if (finishedTask == cancelTask)
{
// wait for the cancellation to take place:
try
{
await sumPageSizesTask;
Console.WriteLine("Download task completed before cancel request was processed.");
}
catch (TaskCanceledException)
{
Console.WriteLine("Download task has been cancelled.");
}
}
You should also check out these documentations for more information on Task cancellation:CancellationTokenSource.Cancel Method (System.Threading) | Microsoft Learn
Task Cancellation - .NET | Microsoft Learn
Hope this clears things up