在我创建的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);
}
对此way服务的调用是通过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);
}
});
我见过一些开发人员这样实现前面的操作:
// 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操作异步对我有什么好处?
发布于 2016-10-21 18:02:18
一种方法是(我已经在客户应用程序中成功地使用了这种方法)让Windows服务对工作线程运行冗长的操作,然后在IIS中这样做,以释放线程,直到阻塞操作完成:注意,这假设结果存储在表中(由jobId标识的行),并在使用几个小时后由一个更干净的进程清理它们。
为了回答这个问题,“考虑到我的问题和上下文,让webAPI操作异步对我有什么好处?”考虑到这是一个“相当长的操作”,我认为是几秒而不是毫秒,这种方法释放了IIS线程。显然,您还必须运行一个windows服务,该服务本身需要占用资源,但这种方法可以防止大量缓慢的查询从系统的其他部分窃取线程。
// 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)
{
var jobID = Guid.NewGuid().ToString()
var job = new Job
{
Id = jobId,
jobType = "GetProductsWithHistory",
pharmacyId = pharmacyId,
page = page,
filter = filter,
Created = DateTime.UtcNow,
Started = null,
Finished = null,
User = {{extract user id in the normal way}}
};
jobService.CreateJob(job);
var timeout = 10*60*1000; //10 minutes
Stopwatch sw = new Stopwatch();
sw.Start();
bool responseReceived = false;
do
{
//wait for the windows service to process the job and build the results in the results table
if (jobService.GetJob(jobId).Finished == null)
{
if (sw.ElapsedMilliseconds > timeout ) throw new TimeoutException();
await Task.Delay(2000);
}
else
{
responseReceived = true;
}
} while (responseReceived == false);
//this fetches the results from the temporary results table
return jobService.GetProductsWithHistory(jobId);
}
https://stackoverflow.com/questions/26158789
复制相似问题