我试图理解异步是如何工作的。这是我的代码:
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";
}
}
有什么不对吗?
答案 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";
}
}