Home > database >  What's happened when await variable which has type Task
What's happened when await variable which has type Task

Time:12-03

I create a Task variable and try to await it just for learning purposes with the next code:

        static async Task Main(string[] args)
        {
            Console.WriteLine("Start");
            Task myTask = new Task(() => { Console.WriteLine("Done"); });
            await myTask;
            Console.WriteLine("Finish");
        }

Application writes Start in the console and then it freezes. I am not sure how to understand whats happened here and why does it freeze. What can be the reason?

I know that usually we apply await to the methods which return Task, but not variable. But vs compiles such code successfully. The expectation was to get all 3 messages in the console.

CodePudding user response:

new Task() creates a new task instance, but does not start it.

so your task never runs, and never has a chance to finish. to fix it you, have to start it first:

static async Task Main(string[] args)
{
    Console.WriteLine("Start");
    Task myTask = new Task(() => { Console.WriteLine("Done"); });

    myTask.Start();

    await myTask;
    Console.WriteLine("Finish");
}

i also recommend reading Microsofts Tutorial on tasks

CodePudding user response:

Do not ever use the Task constructor (link is to my blog). There are literally zero use cases for it that aren't achieved by better means.

If you want to start work running on the thread pool, then use Task.Run:

static async Task Main(string[] args)
{
  Console.WriteLine("Start");
  Task myTask = Task.Run(() => { Console.WriteLine("Done"); });
  await myTask;
  Console.WriteLine("Finish");
}
  • Related