Asp.Net核心长期运行/后台任务

编程入门 行业动态 更新时间:2024-10-21 13:09:56
本文介绍了Asp.Net核心长期运行/后台任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下正确的模式是否可以在Asp.Net Core中实现长期运行的后台工作?还是我应该将 Task.Run / TaskFactory.StartNew 与 TaskCreationOptions一起使用。 LongRunning 选项?

Is the following a correct pattern to implement long running background work in Asp.Net Core? Or should I be using some form of Task.Run/TaskFactory.StartNew with TaskCreationOptions.LongRunning option?

public void Configure(IApplicationLifetime lifetime) { lifetime.ApplicationStarted.Register(() => { // not awaiting the 'promise task' here var t = DoWorkAsync(lifetime.ApplicationStopping); lifetime.ApplicationStopped.Register(() => { try { // give extra time to complete before shutting down t.Wait(TimeSpan.FromSeconds(10)); } catch (Exception) { // ignore } }); }); } async Task DoWorkAsync(CancellationToken token) { while (!token.IsCancellationRequested) { await // async method } }

推荐答案

以下是在Asp.Net Core中实现长期运行的后台工作的正确模式吗?

Is the following a correct pattern to implement long running background work in Asp.Net Core?

是的,是在ASP.NET Core上开始长期运行的基本方法。您当然应该不使用 Task.Run / StartNew / LongRunning -这种方法总是错误的。

Yes, this is the basic approach to start long-running work on ASP.NET Core. You should certainly not use Task.Run/StartNew/LongRunning - that approach has always been wrong.

请注意,您长时间运行的工作可能会在任何时候,这都是正常的。如果您需要更可靠的解决方案,那么您应该在ASP.NET之外有一个单独的后台系统(例如Azure函数/ AWS Lambda)。还有像Hangfire这样的库,可以给您一些可靠性,但也有其缺点。

Note that your long-running work may be shut down at any time, and that's normal. If you need a more reliable solution, then you should have a separate background system outside of ASP.NET (e.g., Azure functions / AWS lambdas). There are also libraries like Hangfire that give you some reliability but have their own drawbacks.

更多推荐

Asp.Net核心长期运行/后台任务

本文发布于:2023-11-15 05:43:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591661.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后台   核心   Asp   Net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!