Running a background thread on a RESTful WebApi request

本小妞迷上赌 提交于 2020-03-04 07:54:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!