简体   繁体   中英

Async/await: Making method async

I'm trying to do a simple example but I'm not even getting the basics. What's wrong with this code? Imagine Calculate() takes a few seconds.

    static void Main(string[] args)
    {
        int result = await Calculate();

        Console.WriteLine(result);
        Console.ReadLine();
    }

    static async Task<int> Calculate()
    {
        return 1;
    }

Simply change your main to:

static void Main(string[] args)
{
    int result = Calculate().Result;

    Console.WriteLine(result);
    Console.ReadLine();
}

As soon as you use the await keyword, the surrounding method must be marked as async which - as others metnioned - is not possible for Main . Since async methods like Calculate still return good old Task objects, feel free to use the "old" way of dealing with them: using Result to wait for results. Of course this is a blocking operation - but no reason to be non-blocking inside Main , right? ;)

You can do this:

static void Main()
{
    WrapMain();
}

static async void WrapMain()
{
    int result = await Calculate();

    Console.WriteLine(result);
    Console.ReadLine();
}

static async Task<int> Calculate()
{
    return await Task.Run(() =>
    {
        return 1;
    });
}

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