简体   繁体   中英

What's happened when await variable which has type Task

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM