Why the TaskCompleted is executed before the end of the operation

Viewed 57

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

1 Answers

Because Task constructors are not async aware. No overloads take an function returning a Task so the task created via constructor and async lambda will finish as soon as first await (of unfinished task) 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.

Related