提问人:nuub 提问时间:11/10/2023 最后编辑:Amit Mohantynuub 更新时间:11/15/2023 访问量:37
如何在WebAPI中请求结束后保持线程运行
how to keep thread runing after request end in webapi
问:
我使用 .NET Framework 4.8 开发了一个 Web 应用程序,在管理线程时遇到了问题。具体来说,我正在我的应用程序中创建后台线程,但它们似乎意外终止,可能是由于垃圾回收。这是我的代码的简化版本:
public class AController : ApiController
{
[HttpPost]
public ResultModel Test()
{
TestService testService = new TestService();
testService.DoSomething();
return new ResultModel();
}
}
public class TestService
{
public void DoSomething()
{
Thread thread = new Thread(() => {
// Perform some work...
});
thread.IsBackground = true;
thread.Start();
}
}
当我向此 API 发出请求时,我收到一个 ResultModel,但不久之后,我的程序遇到了异常(线程已中止)。
您能否帮助我了解为什么这些后台线程被终止,以及我如何确保即使在发送响应后它们也能继续运行?
答:
0赞
Amit Mohanty
11/10/2023
#1
请考虑使用创建后台任务,而不是使用原始线程。这可以与 .使用 时,该任务将成为 ASP.NET 请求管道的一部分,并且不会在主请求线程完成时突然终止。Task.Run
async/await
Task.Run
下面是使用以下示例:Task.Run
public class AController : ApiController
{
private TestService testService = new TestService();
[HttpPost]
public async Task<ResultModel> Test()
{
await testService.DoSomethingAsync();
return new ResultModel();
}
}
public class TestService
{
public async Task DoSomethingAsync()
{
await Task.Run(() => {
// Perform some work...
});
}
}
评论