c# - 异步函数调用异步函数的 C# 性能影响
问题描述
我正在编写代码,最终从另一个异步方法调用异步方法。我想知道这种做法对性能的影响。它是否会导致每个 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
}
推荐阅读
- solr - solr 结果的差异(Web 界面结果与 http 请求结果)
- javascript - 如何在 JavaScript 中以编程方式结束文本合成会话?
- java - GitLab API:如何通过 commit_time 获取分支订单
- java - Java - 从多个数组中获取 n 个元素的组合
- javascript - 是否可以在 Handlebars.js 中提供条件上下文?
- ios - 在 Flutter 中打开原生 UIViewController
- autodesk-forge - 有没有办法在 Autodesk Forge Reality Capture API 上检查每次重建 (photoscene_id) 消耗的云积分?
- sapui5 - 使用聚合增长表
- android - 需要思考?我是否正确清理了我的 ViewModel 类?
- c# - NullReferenceException:如何找到空值