在RESTful WebApi请求上运行后台线程 [英] Running a background thread on a RESTful WebApi request

查看:560
本文介绍了在RESTful WebApi请求上运行后台线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景工作流程: 我有一个客户(jquery/ajax html页面)调用我们的RESTful WebAPI来获取一些数据(患者遭遇"-例如,入院,去诊所等).例如

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;
   }

问题 上面未应用await关键字的"GetEncounters"调用会发生什么情况? 据我了解,异步方法不会生成新线程 因此,当主线程死亡时,这是否意味着对GetEncounters的调用将中止? (在幕后,GetEncounters将触发一个长时间运行的过程来获取数据并将其存储在例如缓存中,以备以后检索.)

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).

如果我单步执行代码,则每个程序都会按预期执行.同样,如果我添加了await关键字,它也可以工作. (但随后我将调用方块设为空白)

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?

推荐答案

解决方案取决于您希望工作的可靠性.也就是说,如果您返回不可用"消息,GetEncounters将对您来说有多重要?

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?

您至少应至少向ASP.NET(即HostingEnvironment.QueueBackgroundWorkItem)注册后台工作.一个更可靠的解决方案可以将后台工作保存在存储中,并具有独立的后端进行处理.我在博客上描述了一些现代方法.

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.

这篇关于在RESTful WebApi请求上运行后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆