在哪里以及如何放置await关键字

时间:2014-01-06 02:18:07

标签: c# async-await

我试图理解异步是如何工作的。这是我的代码:

class Program
{
    static void Main(string[] args)
    {
        Task<string> strReturned = returnStringAsync();
        Console.WriteLine("hello!");
        string name = await strReturned; //error: The 'await' operator can only be used 
                                         //within an async method. Consider marking this 
                                         //method with the 'async' modifier and changing 
                                         //its return type to 'Task'

        Console.WriteLine(name);
    }

    static async Task<string> returnStringAsync()
    {
        Thread.Sleep(5000);
        return "Richard"; 
    }
}

有什么不对吗?

1 个答案:

答案 0 :(得分:1)

这有效

class Program
{
    static void Main(string[] args)
    {
        Task<string> str = returnStringAsync();
        Console.WriteLine("hello!");

        string name = str.Result;

        Console.WriteLine(name);
    }

    static async Task<string> returnStringAsync()
    {
        await Task.Delay(5000);
        return "Richard"; 
    }
}