首页 > 解决方案 > 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.

标签: asynchronousautomapper-6

解决方案


由于“_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;
}

推荐阅读