I have the following operation in a Web API I created:

// 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);
}

The call to this webservice is done through a Jquery Ajax call this way:

$.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);
      }          
  });

I've seen some developers that implement the previous operation this way:

// 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));
}

Gotta say, though, that GetProductsWithHistory() is a quite long operation. Given my problem and context, how will making the webAPI operation asynchronous benefit me?

推荐答案

In your specific example the operation is not asynchronous at all so what you're doing is async over sync. You're just releasing one thread and blocking another. There's no reason to that, because all threads are thread pool threads (unlike in a GUI application).

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.

From Should I expose asynchronous wrappers for synchronous methods?

However when making WebAPI calls async where there's an actual asynchronous operation (usually I/O) instead of blocking a thread that sits and waits for a result the thread goes back to the thread pool and so able to perform some other operation. Over all that means that your application can do more with less resources and that improves scalability.

Jquery相关问答推荐

如何在光滑的轮播上添加进度条

使用 Bootstrap 3 下拉菜单作为上下文菜单

与其他 Javascript 框架相比,为什么 jQuery 被如此广泛地采用?

jQuery在点击函数后获取
  • 元素的id/value
  • jQuery函数从数组中获取所有唯一元素?

    如何在 jQuery 中获取浏览器滚动位置?

    如何使用jquery取消绑定所有事件

    SCRIPT7002:XMLHttpRequest:网络错误 0x2ef3,由于错误 00002ef3 无法完成操作

    如何设置缓存:jQuery.get 调用中的 false

    动态设置 iframe src

    Backbone.js 和 jQuery

    如何从表格单元格 (td) 中获取相应的表格标题 (th)?

    将字符串true和false转为布尔值

    如何在 Angular 4 中使用 jQuery 插件?

    使用 jQuery 拖放防止单击事件

    使用 MVC、C# 和 jQuery 导出为 CSV

    jQuery ajax (jsonp) 忽略超时并且不触发错误事件

    如何签入用户已在 Google recaptcha 中选中复选框的 js?

    用作 Google Chrome 书签

    将多个参数传递给 jQuery ajax 调用