【发布时间】:2014-01-06 02:18:06
【问题描述】:
我正在尝试了解异步的工作原理。这是我的代码:
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";
}
}
有什么问题吗?
【问题讨论】:
-
那么,你不明白错误告诉你什么?
-
错误在strReturned旁边。
-
在
async方法中,您应该使用await Task.Delay(5000)而不是Thread.Sleep(5000)。 -
@PhillipScottGivens 不,它不会编译
-
@Richard77:您可能会发现我的async/await intro 很有帮助。
标签: c# async-await