以下正确的模式是否可以在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核心长期运行/后台任务
发布评论