Asyncawait 只有在允许机器完成额外工作时才会提高性能
请考虑以下代码:
public async Task MethodA()
{
await MethodB();
// Do other work
}
public async Task MethodB()
{
await MethodC();
// Do other work
}
public async Task MethodC()
{
// Or await some other async work
await Task.Delay(100);
}
这不会比任何表现更好
public void MethodA()
{
MethodB();
// Do other work
}
public void MethodB()
{
MethodC();
// Do other work
}
public void MethodC()
{
Thread.Sleep(100);
}
async / await 的主要目的是允许机器执行其他工作 - 例如,允许调用线程在等待某些 I / O 操作的结果时执行其他工作。在这种情况下,调用线程永远不会被允许做比其他情况下更多的工作,所以与仅仅同步调用 MethodA()
,MethodB()
和 MethodC()
相比,没有性能提升。