c# - 为什么我应该创建异步 WebAPI 操作而不是同步操作?

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

我在我创建的 Web API 中有以下操作:

// GET api/<controller>
[HttpGet]
[Route("pharmacies/{pharmacyId}/page/{page}/{filter?}")]
public CartTotalsDTO GetProductsWithHistory(Guid pharmacyId, int page, string filter = null ,[FromUri] bool refresh = false)
{
    return delegateHelper.GetProductsWithHistory(CustomerContext.Current.GetContactById(pharmacyId), refresh);
}

通过 Jquery Ajax 调用以这种方式调用此 Web 服务:

$.ajax({
      url: "/api/products/pharmacies/<%# Farmacia.PrimaryKeyId.Value.ToString() %>/page/" + vm.currentPage() + "/" + filter,
      type: "GET",
      dataType: "json",
      success: function (result) {
          vm.items([]);
          var data = result.Products;
          vm.totalUnits(result.TotalUnits);
      }          
  });

我见过一些开发者是这样实现前面操作的:

// GET api/<controller>
[HttpGet]
[Route("pharmacies/{pharmacyId}/page/{page}/{filter?}")]
public async Task<CartTotalsDTO> GetProductsWithHistory(Guid pharmacyId, int page, string filter = null ,[FromUri] bool refresh = false)
{
    return await Task.Factory.StartNew(() => delegateHelper.GetProductsWithHistory(CustomerContext.Current.GetContactById(pharmacyId), refresh));
}

不过,必须说 GetProductsWithHistory() 是一个相当长的操作。考虑到我的问题和上下文,使 webAPI 操作异步对我有何好处?

最佳答案

在您的特定示例中,该操作根本不是异步的,因此您所做的是异步优于同步。您只是释放一个线程并阻塞另一个线程。没有理由这样做,因为所有线程都是线程池线程(与 GUI 应用程序不同)。

In my discussion of “async over sync,” I strongly suggested that if you have an API which internally is implemented synchronously, you should not expose an asynchronous counterpart that simply wraps the synchronous method in Task.Run.

来自 Should I expose asynchronous wrappers for synchronous methods?

然而,当 WebAPI 调用 async 时,那里有一个实际的异步操作(通常是 I/O),而不是阻塞一个等待结果的线程,该线程返回到线程池等能够执行一些其他操作。总而言之,这意味着您的应用程序可以用更少的资源做更多的事情,并提高了可扩展性。

关于c# - 为什么我应该创建异步 WebAPI 操作而不是同步操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26158789/

相关文章:

jquery - 在一个 div 动画之后仍然落后于其他 div

javascript - 如何检查 jQuery 数据表中特定列的每个值?

c# - 单元测试在 try catch block 中调用异步操作的 getter

c# - ASP.NET DropDownList SelectedIndex 在第一个元素上未更改

javascript - 向父选项卡发送 Flash 成功消息

javascript - 如何将 Rx.Observable.fromEvent 添加到 ajax 内容

javascript - 在通过 jquery 或 ajax 加载内容之前显示加载图像

jquery - 路由ajax Rails 麻烦

c# - 将小数转换为整数

c# - 如何使用 Telerik Rad 网格绑定(bind)将数据传递给 Ajax 服务?