问题
Background Workflow: I have a client (jquery/ajax html page) calling our RESTful WebAPI to get some data (Patient 'encounters' - e.g. admission to a hospital, visit to a clinic, etc.). e.g.
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;
}
Question What happens the "GetEncounters" call above where the await keyword is not applied? From my understanding, async methods do NOT generate a new thread so when the main thread dies, does that mean the call to GetEncounters will abort? (Behind the scenes, the GetEncounters will fire off a long running process to get data and store it in, e.g. cache, for later retrieval).
If I step through the code, every executes as expected. Likewise, if I add in the await keyword, it also works. (But then I make the caller block)
What's the solution? i.e. what is the best way to create a background task/thread to execute the code even though the main thread has died?
回答1:
The solution depends on how reliable you want the work to be. I.e., if you return the "not available" message, how important is it to you that GetEncounters
will run?
You should at the very least register the background work with ASP.NET (i.e., HostingEnvironment.QueueBackgroundWorkItem
). A more reliable solution would save the background work in storage and have an independent backend for processing. I describe some modern approaches on my blog.
来源:https://stackoverflow.com/questions/24272739/running-a-background-thread-on-a-restful-webapi-request