首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么要创建异步WebAPI操作而不是同步操作?

为什么要创建异步WebAPI操作而不是同步操作?
EN

Stack Overflow用户
提问于 2014-10-02 18:19:15
回答 1查看 85.2K关注 0票数 112

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

代码语言:javascript
复制
// 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调用完成的,如下所示:

代码语言:javascript
复制
$.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);
      }          
  });

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

代码语言:javascript
复制
// 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操作异步对我有什么好处?

EN

回答 1

Stack Overflow用户

发布于 2016-10-21 18:02:18

一种方法是(我已经在客户应用程序中成功地使用了这种方法)让Windows服务对工作线程运行冗长的操作,然后在IIS中这样做,以释放线程,直到阻塞操作完成:注意,这假设结果存储在表中(由jobId标识的行),并在使用几个小时后由一个更干净的进程清理它们。

为了回答这个问题,“考虑到我的问题和上下文,让webAPI操作异步对我有什么好处?”考虑到这是一个“相当长的操作”,我认为是几秒而不是毫秒,这种方法释放了IIS线程。显然,您还必须运行一个windows服务,该服务本身需要占用资源,但这种方法可以防止大量缓慢的查询从系统的其他部分窃取线程。

代码语言:javascript
复制
// 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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26158789

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档