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.
I think that your confusion is about the cancellation token that you pass in into the
Task.Runmethod.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)
This token can only be used in the few milliseconds between where you call the method
Task.Runand 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.Runare thrown again when you await the result ofTask.Run. This means that if you have anOperationCancelledExceptionthrown inside theInitializeAsync, this will cause theawait Task.Runto rethrow this exception, skipping the rest of this method.