简体   繁体   中英

Why the console exits even after using await?

using System;
using System.Threading;
using System.Threading.Tasks;

namespace application
{
    public class Files
    {
        public static Task<string> runTask()
        {
            return Task.Run(() =>
            {
                Thread.Sleep(2000);
                return "Hello World!";
            });
        }

        public static async void Hello()
        {   
            string result = await runTask();
            Console.WriteLine(result);
            Console.WriteLine("Execution Ended!");
        }

        public static void Main(string[] args)
        {
            Hello();
            Console.WriteLine("The Async Code Is Running Above!");
        }

    };
};

The above C# code just prints "The Async Code Is Running Above." and nothing happens after that.

How can I make this print things in following order (And where I'm going wrong):

"The Async Code Is Running Above!" "Hello World!" "Execution Ended!"

Thankyou!

There are a two main points in your question. First, don't use Thread.Sleep inside asynchronous methods, use Task.Delay instead. Second, you can make Main method async as well and return a Task to get an expected behavior (it's possible starting from C# 7.1 )

public static Task<string> runTask()
{
    return Task.Run(async () =>
    {
        await Task.Delay(2000);
        return "Hello World!";
    });
}

public static async Task Hello()
{
    string result = await runTask();
    Console.WriteLine(result);
    Console.WriteLine("Execution Ended!");
}

static async Task Main()
{
    await Hello();
    Console.WriteLine("The Async Code Is Running Above!");
}

Avoid using void async methods, try returning tasks always. Check this post for more details async-await-when-to-return-a-task-vs-void

class Files
{
    static void Main(string[] args)
    {
        Task t = Hello();
        Console.WriteLine("The Async Code Is Running Above!");

        //Wait for the task to complete
        //Dont use this code in UI applications which will cause blocking
        t.Wait();

        //keep the application open
        Console.ReadLine();
    }

    public static Task<string> runTask()
    {
        return Task.Run(async () =>
       {
           await Task.Delay(2000);
           return "Hello World!";
       });
    }

    public static async Task Hello()
    {
        string result = await runTask();
        Console.WriteLine(result);
        Console.WriteLine("Execution Ended!");
    }

}

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