Dav*_*nez 109 c# ajax jquery async-await asp.net-web-api
我在我创建的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);
}
Run Code Online (Sandbox Code Playgroud)
对此Web服务的调用是通过以下方式通过Jquery Ajax调用完成的:
$.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);
}
});
Run Code Online (Sandbox Code Playgroud)
我见过一些以这种方式实现上一个操作的开发人员:
// 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));
}
Run Code Online (Sandbox Code Playgroud)
但是,必须说,GetProductsWithHistory()是一个相当长的操作.鉴于我的问题和背景,如何使webAPI操作异步对我有益?
i3a*_*non 96
在您的具体示例中,操作根本不是异步的,因此您所做的是异步过度同步.你只是释放一个线程并阻止另一个线程.没有理由这样做,因为所有线程都是线程池线程(与GUI应用程序不同).
在我对"异步过同步"的讨论中,我强烈建议如果你有一个内部同步实现的API,你就不应该公开一个简单包装同步方法的异步对应物
Task.Run
.
From 我应该为异步方法公开同步包装器吗?
但是,当进行WebAPI调用时async
,如果存在实际的异步操作(通常是I/O),而不是阻塞位于并等待结果的线程,则线程将返回到线程池,从而能够执行其他操作.总之,这意味着您的应用程序可以用更少的资源完成更多工作并提高可伸缩性.
归档时间: |
|
查看次数: |
80047 次 |
最近记录: |