Home > OS >  Why the TaskCompleted is executed before the end of the operation
Why the TaskCompleted is executed before the end of the operation

Time:05-24

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

CodePudding user response:

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.

  • Related