可能重复:
Why does the async keyword exist
我有两种方法。一种是普通方法(MyMethod
),另一种是异步方法(MyMethodAsync
)。我得到一个编译错误。
static string MyMethod()
{
var result = await MyMethodAsync(); // compile error here
return result;
}
async static Task<string> MyMethodAsync()
{
/** perform my logic here... **/
Thread.Sleep(1000);
return "yes";
}
错误消息是
“Acess”运算符只能在异步方法中使用。考虑使用“async”修饰符标记此方法,并将其返回类型更改为“task”。
我很困惑。当我使用
await
关键字时,调用线程将挂起并等待任务完成。因此,一旦await
被使用,该方法就不再是异步方法。对吗?备注:我知道我应该把逻辑放入
MyMethod
和MyMethodAsync
调用MyMethod
来实现我想要的。 最佳答案
async
关键字的整个要点是启用await
关键字。
我收集了一些“为什么关键字的工作方式?”问题on my blog。“为什么不能通过async
推断await
?”answered conclusively by Eric Lippert on his blog简而言之,有两个原因:向后兼容和代码可读性。