请考虑 ASP.NET Core Controller 中的异步 GetAccountProperties 方法:
public class CreditAccountController : Microsoft.AspNetCore.Mvc.Controller
{
private readonly ICreditAccountManager _creditAccountManager;
public CreditAccountController(
ICreditAccountManager creditAccountManager
{
_creditAccountManager = creditAccountManager;
}
[HttpGet]
public async Task<IActionResult> GetAccountProperties(...)
{
var result = await _creditAccountManager.GetPropertiesAsync(...);
if (accountResult.Code == ResponseCode.Success)
return Ok(result.Value);
else
return NotFound();
}
}
以及 CreditAccountManager 存储库中 GetPropertiesAsync() 方法的以下实现。
第一个实现使用 .ToList() 方法:
public Task<Result<List<GeneralAccount>>> GetAccountPropertiesAsync(...)
{
var properties = _generalDatabaseContext.AccountProperties.Where(...).ToList();
result.Code = ResponseCode.Success;
result.Value = accounts;
return Task.FromResult(result);
}
第二个使用 .ToListAsync() 方法和嵌套的 async/await:
public async Task<Result<List<GeneralAccount>>> GetAccountPropertiesAsync(...)
{
var properties = await _generalDatabaseContext.AccountProperties.Where(...).ToListAsync();
result.Code = ResponseCode.Success;
result.Value = accounts;
return result;
}
考虑到存储库方法中没有其他 EF 调用,并且 Controller 的方法已经是异步的,存储库方法的哪个实现在性能方面更好?
最佳答案
就性能而言,ToListAsync
可能性能更差,因为异步总是带来开销。
这并不是人们使用异步的真正原因。 由于您的数据库调用基本上是异步的,因此在同步选项中,您的服务器线程会等待数据库调用完成,然后再运行其余工作并返回结果。
在异步方法中,线程可以在等待数据库调用完成时处理其他请求。 因此它提供了更好的吞吐量。 我会一直使用异步方法,因为将 Controller 操作标记为异步然后同步执行最大的 IO 操作是毫无意义的。
也就是说,考虑性能的最佳选择是衡量。 进行一项同步操作和另一项异步操作。 然后测量单个请求响应时间和吞吐量。 然后,您可以根据实际数字做出决定。
关于c# - Entity Framework 核心 : ToList() vs ToListAsync(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52588644/