gpt4 book ai didi

c# - Asp.Net 核心长时间运行/后台任务

转载 作者:IT王子 更新时间:2023-10-29 04:47:27 29 4
gpt4 key购买 nike

以下是在 Asp.Net Core 中实现长时间运行的后台工作的正确模式吗?或者我应该使用某种形式的 Task.Run/TaskFactory.StartNewTaskCreationOptions.LongRunning 选项吗?

    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.0 IHostedService。这是 documentation .从 .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 ...
}
}

在您的初创公司中,您只需注册类(class):

public static IServiceProvider Build(IServiceCollection services)
{
//.....
services.AddSingleton<IHostedService, UpdateBackgroundService>();
services.AddTransient<IHostedService, UpdateBackgroundService>(); //For run at startup and die.
//.....
}

关于c# - Asp.Net 核心长时间运行/后台任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45013054/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com