asynchronous - Should I return result of AutoMapper using await Task.FromResult() in an async method?
问题描述
All my repository methods are async for my CRUD operations using EF.Core async methods and use AutoMapper to map my EF entity model (Customer) to Domain Model (CustomerModel) and pass it back to my service layer.
public async Task<CustomerModel> GetCustomerByIdAsync(int id)
{
Customer customer = await _context.Customers.FindAsync(id);
var mappedResult = _mapper.Map<CustomerModel>(customer);
return await Task.FromResult(mappedResult);
}
Since "_mapper.Map" is not async but GetCustomerByIdAsync is, I return await Task.FromResult(mappedResult) instead of return mappedResult;
My caller method in service layer is also async. Have I got this right? I am also wondering about deadlock implications, although I am not calling any of my async methods from sync methods using .Result.
Thanks for your time.
解决方案
由于“_mapper.Map”不是异步的,但 GetCustomerByIdAsync 是异步的,所以我返回 await Task.FromResult(mappedResult) 而不是 return mappedResult;
不,await Task.FromResult(x)
从来没有任何意义。我已经看过很多这段代码,但我不确定它来自哪里。
await Task.FromResult(x)
从字面上看,这是一种效率较低的写作方式x
。它的效率较低且可维护性较差,所以我不知道这个想法是从哪里来的。
您的代码应如下所示:
public async Task<CustomerModel> GetCustomerByIdAsync(int id)
{
Customer customer = await _context.Customers.FindAsync(id);
var mappedResult = _mapper.Map<CustomerModel>(customer);
return mappedResult;
}
推荐阅读
- ruby-on-rails - Rails 5.2 / Ruby 2.5:如何消除垃圾邮件 WEBrick 请求日志?
- laravel - 安排电子邮件在用户提交表单后 40 分钟使用 mailgun 发送
- r - 麻烦创建地图(ggplot)和按属性着色
- nestjs - 我如何在 CustomRepository(nestjs) 中使用 DI
- json - 快速向 JSON 的主体添加值
- node.js - 找不到模块
- javascript - 不能使用 stopProgagation 和 preventDefault 来停止打开链接
- vba - 为什么从最新的电子邮件跳过文件循环进入电子邮件收件箱?
- c# - 如果我从数据库中删除外键约束,实体框架的导航属性会起作用吗?
- spring-boot - 在 Spring Cloud 中使用 @RefreshScope 重新加载弹簧属性时出错