1

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();
    }
}
user33276346
  • 1,501
  • 1
  • 19
  • 38
  • 2
    Your code does not check the status of the cancellation token. – Progman Mar 05 '23 at 17:47
  • Then why, it throws sometimes? – user33276346 Mar 05 '23 at 17:51
  • 3
    Because sometimes it gets cancelled before the task starts – Charlieface Mar 05 '23 at 17:52
  • 2
    So if the task is cancelled before it starts, it throws and doesn't ever start. But if the task has already started it depends on me to throw with ThrowIfCancellationRequested. Thank you! – user33276346 Mar 05 '23 at 17:55
  • 1
    Check out this article by Stephen Cleary: [A Tour of Task, Part 9: Delegate Tasks](https://blog.stephencleary.com/2015/03/a-tour-of-task-part-9-delegate-tasks.html). It should answer all your questions about using the `Task.Run` with `CancellationToken` argument. – Theodor Zoulias Mar 05 '23 at 18:21

0 Answers0