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

Why the TaskCompleted is executed before the end of the operation

I created a task like the following code

Task task = new(async () =>
{
    // without await Task Delay dont work
    await Task.Delay(TimeSpan.FromSeconds(5));
    Console.WriteLine("Task is down");
});

task.Start();

var awaiter = task.GetAwaiter();

awaiter.OnCompleted(() =>
{
    Console.WriteLine("Task is Completed");
});

Why the task completed first is printed and then the task is down
The task is complete and will be printed if my operation is not finished yet

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 :

Because Task constructors are not async aware. No overloads take an action accepting Task so the task created via constructor and async lambda will finish as soon as first await is encountered.

And in general you should try avoid using Task constructors and prefer Task.Run instead. From the docs:

This constructor should only be used in advanced scenarios where it is required that the creation and starting of the task is separated.
Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static Task.Run(Action) or TaskFactory.StartNew(Action) method.

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