Asp.Net核心长期运行/后台任务
以下是在Asp.Net Core中实现长时间运行后台工作的正确模式吗? 或者我应该使用TaskCreationOptions.LongRunning
选项的某种forms的Task.Run
/ TaskFactory.StartNew
?
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中实现长时间运行后台工作的正确模式吗?
是的,这是启动ASP.NET Core长期运行工作的基本方法。 你当然不应该使用Task.Run
/ StartNew
/ LongRunning
– 这种方法一直都是错误的。
请注意,您的长时间工作可能会随时关闭,这是正常的。 如果您需要更可靠的解决方案,那么您应该在ASP.NET之外拥有一个单独的后台系统(例如,Azure functions / AWS lambdas)。 还有像Hangfire这样的库可以提供一些可靠性,但也有其自身的缺点。
另请IHostedService
.NET Core 2.0 IHostedService
。 这是文档 。 从.NET Core 2.1开始,我们将使用BackgroundService
抽象类。 它可以像这样使用:
public class UpdateBackgroundService: BackgroundService { private readonly DbContext _context; public UpdateTranslatesBackgroundService(DbContext context) { this._context= context; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await ... } }
在您的创业公司中,您只需注册课程:
public static IServiceProvider Build(IServiceCollection services) { //..... services.AddSingleton(); services.AddTransient(); //For run at startup and die. //..... }
- IFormFile没有被dropzone uploadMultiple请求填充
- ASP.NET Core 2 – 身份 – 自定义角色的DI错误
- 将.Net Core构建为EXE而不是DLL
- 如何从Entity Framework Core中的DbContext获取列名和相应的数据库类型
- Swashbuckle.AspNetCore v1.0.0 with OAuth2,flow:application – > IdentityServer4
- 无法在.NET Core中编译Environment.Exit
- 在.NET Core中引用时,从程序集文件加载的类型不等于相同的类型
- 如何添加通用dependency injection
- 通过.NET Core上的MEF将参数传递给插件构造函数?