Trying to learn cancellation tokens. Not sure why this does not work

65 Views Asked by At

So, I'm learning Cancellation tokens and I'm trying this example. The writeline is never working even if I cancel this method from the outside.

So how this works, is the initializeAsync, if it takes too long, I have another method that cancels this task and then needs to alert the end user it was cancelled. However, the writeline never happens when it is cancelled from an outside method. _cancelTask is shared on the other method as well.


 internal static async Task<bool> SimConnectInitAsync()
  {
      _cancelTask = new CancellationTokenSource();

      await Task.Run(async ()=>
      {
          await InitializeAsync();
      }, _cancelTask.Token);

      Debug.WriteLine("Cancelled");
      _cancelTask.Cancel();
      _cancelTask.Dispose();

      return true;
  }

Never get writeline to trigger. Cancels the entire method.

1

There are 1 best solutions below

0
Christophe Devos On

I think that your confusion is about the cancellation token that you pass in into the Task.Run method.

This token is only used if the task hasn't started yet. See the documentation at https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.run?view=net-8.0#system-threading-tasks-task-run(system-func((system-threading-tasks-task))-system-threading-cancellationtoken)

A cancellation token that can be used to cancel the work if it has not yet started.

This token can only be used in the few milliseconds between where you call the method Task.Run and that the inner task has found a thread to start it's work on. Once the inner task has started, then this cancellation token is no longer used.

Also, errors that are thrown inside of the method passed to Task.Run are thrown again when you await the result of Task.Run. This means that if you have an OperationCancelledException thrown inside the InitializeAsync, this will cause the await Task.Run to rethrow this exception, skipping the rest of this method.