Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Task does not complete if another task with in it gets cancelled

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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");
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading