有效地将 async/await 与 ASP.NET Web API 结合使用 [英] Effectively use async/await with ASP.NET Web API

查看:58
本文介绍了有效地将 async/await 与 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.

这篇关于有效地将 async/await 与 ASP.NET Web API 结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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