我在我创建的 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/