In this code, the task t
will never complete (never outputs to the console) if I cancel the token, even though the token is not used for t
and only used for a task inside t
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
Task t = Task.Factory.StartNew(async () =>
{
await Task.Delay(1000, token);
Console.WriteLine("Task Completed");
});
source.Cancel();
How can I cancel the token but also let the task complete
Notes:
I tried using Task.Run
instead, and got the same output
t.IsCompleted
will stay false indefinitely (task will never complete)
The delay task does complete
CodePudding user response:
You can make the t
to survive the cancellation, by handling and suppressing the OperationCanceledException
that is thrown by the Task.Delay
:
Task t = Task.Run(async () =>
{
try { await Task.Delay(1000, token); } catch (OperationCanceledException) { }
Console.WriteLine("Task Completed");
});