通过ASP.NET Web API有效地使用异步/等待 [英] Effectively use async/await with ASP.NET Web API

查看:159
本文介绍了通过ASP.NET Web API有效地使用异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的Web API项目中使用ASP.NET的async/await功能.我不太确定这是否会对我的Web API服务的性能产生任何影响.请从我的应用程序下面找到工作流程和示例代码.

I am trying to make use of the async/await feature of ASP.NET in my Web API project. I am not very sure whether it will make any difference in performance of my Web API service. Please find below the workflow and sample code from my application.

工作流程:

UI应用程序→Web API端点(控制器)→Web API服务层中的调用方法→调用另一个外部Web服务. (这里有数据库交互等)

UI Application → Web API endpoint(controller) → Call method in Web API service layer → Call another external web service. (Here we have the DB interactions, etc.)

控制器:

public async Task<IHttpActionResult> GetCountries()
{
    var allCountrys = await CountryDataService.ReturnAllCountries();

    if (allCountrys.Success)
    {
        return Ok(allCountrys.Domain);
    }

    return InternalServerError();
}

服务层:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
    var response = _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");

    return Task.FromResult(response);
}

我测试了上面的代码,并且正在工作.但是我不确定async/await是否正确使用.请分享您的想法.

I tested the above code and is working. But I am not sure whether it is the correct usage of async/await. Please share your thoughts.

推荐答案

我不太确定这是否会对我的API的性能产生任何影响.

I am not very sure whether it will make any difference in performance of my API.

请记住,服务器端异步代码的主要好处是可扩展性.它不会神奇地使您的请求运行得更快.我在async文章中介绍了几个我应该使用async"注意事项ASP.NET .

Bear in mind that the primary benefit of asynchronous code on the server side is scalability. It won't magically make your requests run faster. I cover several "should I use async" considerations in my article on async ASP.NET.

我认为您的用例(调用其他API)非常适合异步代码,请记住异步"并不意味着更快".最好的方法是首先使您的 UI 响应和异步;即使您的应用稍慢一些,这也会使您的应用感觉更快.

I think your use case (calling other APIs) is well-suited for asynchronous code, just bear in mind that "asynchronous" does not mean "faster". The best approach is to first make your UI responsive and asynchronous; this will make your app feel faster even if it's slightly slower.

就代码而言,这不是异步的:

As far as the code goes, this is not asynchronous:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
  var response = _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
  return Task.FromResult(response);
}

您需要一个真正的异步实现来获得async的可伸缩性优势:

You'd need a truly asynchronous implementation to get the scalability benefits of async:

public async Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
  return await _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}

或者(如果您在此方法中的逻辑确实只是传递):

Or (if your logic in this method really is just a pass-through):

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
  return _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}

请注意,像这样从由内而外"工作比从由内而外"工作更容易.换句话说,不要以异步控制器动作开始,然后强制下游方法是异步的.相反,请确定自然的异步操作(调用外部API,数据库查询等),并首先使它们在最低级别(Service.ProcessAsync)异步.然后,使async滴流,最后一步使您的控制器动作异步.

Note that it's easier to work from the "inside out" rather than the "outside in" like this. In other words, don't start with an asynchronous controller action and then force downstream methods to be asynchronous. Instead, identify the naturally asynchronous operations (calling external APIs, database queries, etc), and make those asynchronous at the lowest level first (Service.ProcessAsync). Then let the async trickle up, making your controller actions asynchronous as the last step.

在这种情况下,在任何情况下都不应使用Task.Run.

And under no circumstances should you use Task.Run in this scenario.

这篇关于通过ASP.NET Web API有效地使用异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆