2014-06-17 37 views
1

后台工作流程: 我有一个客户端(jquery/ajax html页面)调用我们的RESTful WebAPI来获取一些数据(Patient'遭遇') - 例如进入医院,访问诊所等)。例如在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关键字,它也可以。 (但后来我打来电者)

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

回答

3

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

您应该至少注册ASP.NET的后台工作(即,HostingEnvironment.QueueBackgroundWorkItem)。更可靠的解决方案可以节省后台存储工作量,并拥有独立的后端进行处理。我描述了some modern approaches on my blog