如何创建方法需要任务lambda表达式异步

时间:2016-11-07 18:12:02

标签: c# asp.net-web-api async-await

public async Task<HttpResponseMessage> getOne(HttpRequestMessage request, int id)
{ 

   return CreateResponse(async () =>
    {
        var category = await _unitOfWork.Categories.GetSingleAsync(id);
        var categoryVm = Mapper.Map<Category, CategoryViewModel>(category);

        HttpResponseMessage response = request.CreateResponse<CategoryViewModel>(HttpStatusCode.OK, categoryVm);

        return response;
    });
}

基类

protected Task<IHttpActionResult> CreateResponse(Func<IHttpActionResult, Task> function)
{
    IHttpActionResult response = null;
    try
    {
        response = function.Invoke();

    }
}

1 个答案:

答案 0 :(得分:1)

阅读跨领域问题

你给自己带来了不必要的麻烦。您的示例可以简化为:

public async Task<IHttpActionResult> getOne(int id) {
    var category = await _unitOfWork.Categories.GetSingleAsync(id);
    var categoryVm = Mapper.Map<Category, CategoryViewModel>(category);
    return Ok(categoryVm);
}

尽量保持控制器的精益。

检查this回答