If I modify the following code by putting the cancel before creating the task it always stops in the catch. However, if I run it as it is, sometimes stops in the catch, but other times it will print numbers indefinitely.
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var tokenSource = new CancellationTokenSource();
var task = Task.Run(() =>
{
int i = 0;
while (true)
{
Console.WriteLine($"{i++}");
}
}, tokenSource.Token);
tokenSource.Cancel();
try
{
await task;
}
catch (OperationCanceledException e)
{
Console.WriteLine($"{nameof(OperationCanceledException)} thrown with message: {e.Message}");
}
finally
{
tokenSource.Dispose();
}
Console.ReadKey();
}
}