以下是在 Asp.Net Core 中实现长时间运行的后台工作的正确模式吗?或者我应该使用某种形式的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
}
}
另请检查 .NET Core 2.0IHostedService
。这里是文档。从 .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<IHostedService, UpdateBackgroundService>();
services.AddTransient<IHostedService, UpdateBackgroundService>(); //For run at startup and die.
//.....
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)