Skip to main content
 首页 » 编程设计

c#之在 RESTful WebApi 请求上运行后台线程

2024年02月06日29myhome

后台工作流程: 我有一个客户端(jquery/ajax html 页面)调用我们的 RESTful WebAPI 来获取一些数据(患者“遭遇”——例如入院、就诊等)。例如

public async Task<string> GetEncounters(string patientId) 
{ 
        PatientChart patientChart = await _myService.GetPatientChart(patientId); 
 
        string message = string.Empty; 
        if (patientChart.Encounters.Status == PatientChart.StatusNotApplicable) 
        { 
            message = "List of Encounters is not available. A request has been made to retrieve it."; 
            _myService.GetEncounters(patientId); // async method without call to await 
        } 
 
        return message; 
   } 

问题 上面没有应用 await 关键字的“GetEncounters”调用会发生什么情况? 据我了解,异步方法不会生成新线程 因此,当主线程终止时,是否意味着对 GetEncounters 的调用将中止? (在幕后,GetEncounters 将启动一个长时间运行的进程以获取数据并将其存储在缓存中,以供以后检索)。

如果我单步执行代码,每个代码都会按预期执行。同样,如果我添加 await 关键字,它也会起作用。 (但后来我让调用者阻塞)

解决方案是什么? 即,创建后台任务/线程以执行代码的最佳方法是什么,即使主线程已经死亡?

请您参考如下方法:

解决方案取决于您希望工作的可靠性。即,如果您返回“不可用”消息,GetEncounters 将运行对您来说有多重要?

您至少应该使用 ASP.NET 注册后台工作(即 HostingEnvironment.QueueBackgroundWorkItem)。更可靠的解决方案是将后台工作保存在存储中,并有一个独立的后端进行处理。我描述了some modern approaches on my blog .