我在编写代码时最终从另一个异步方法调用了异步方法。我想知道这种做法对性能的影响。是否会导致每个 async-await 使用这么多线程?
一个例子会有所帮助
public async Task<IHttpActionResult> ControllerMethod()
{
:
return await A1();
}
public async Task<R1> A1()
{
:
var result = await A2();
if (result != null)
{
A3()
}
return result;
}
public async Task<R1> A2()
{
:
var result = await A4();
return result;
}
public void A3()
{
:
// call to another async method without await
}
请帮助我理解 - 这是不好的做法吗?这是重构代码的结果
最佳答案
成本和性能影响在于每个被标记为异步的方法都被转移到幕后的状态机中;因此必须处理更多的代码和状态机实例。
您可以通过重写来避免状态机,如下所示;如果该语句后面没有代码,则不必等待,只需按照下面的 A2 方法返回任务即可。
public Task<IHttpActionResult> ControllerMethod()
{
return A1();
}
public async Task<R1> A1()
{
var result = await A2();
if (result != null)
{
A3()
}
return result;
}
public Task<R1> A2()
{
return A4();
}
public void A3()
{
// call to another async method without await
}
关于异步函数调用异步函数的 C# 性能影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50530810/