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

www.365466.com 📅 2025-07-29 13:41:26 ✍️ admin 👁️ 8734 ❤️ 328
为什么要创建异步WebAPI操作而不是同步操作?

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

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

代码语言:javascript运行复制// GET api/

[HttpGet]

[Route("pharmacies/{pharmacyId}/page/{page}/{filter?}")]

public async Task 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);

}

相关创意

王者荣耀未成年人防沉迷限制
谈笑风声哪个字错
辞海打一成语:简单易懂的谜语及答案
没有找到站点
货运等级详解 什么是货运等级?
交换机的接口有哪些?一文带你记住其名称及作用
国产自拍app有哪些?8款国产自拍app下载推荐
潜艇有是什么意思    潜艇指挥官说有是什么意思
谯阁是什么意思