嗨,我在使用IHostedService为我的后台服务运行长时间任务时遇到了问题,但它确实可以正常工作,但从长远来看,后台服务由于此线程退出的代码而突然停止:
The thread 10824 has exited with code 0 (0x0).
The thread 12340 has exited with code 0 (0x0).
The thread 9324 has exited with code 0 (0x0).
The thread 11168 has exited with code 0 (0x0).
The thread 11616 has exited with code 0 (0x0).
The thread 9792 has exited with code 0 (0x0).
我将后台服务注册为
//Register Background
serviceCollection.AddSingleton<CoinPairBackgroundService>
serviceCollection.AddSingleton<SaveFakePersonBackgroundService>();
serviceCollection.AddSingleton<LeaderboardMinutesBackgroundService>();
serviceCollection.AddSingleton<LeaderboardHoursBackgroundService>();
serviceCollection.AddSingleton<IHostedService, CoinPairBackgroundService>();
serviceCollection.AddSingleton<IHostedService, SaveFakePersonBackgroundService>();
serviceCollection.AddSingleton<IHostedService, LeaderboardMinutesBackgroundService>();
serviceCollection.AddSingleton<IHostedService, LeaderboardHoursBackgroundService>();
因为将来我想使用]手动打开和关闭后台服务>
IServiceProvider provider = _serviceProvider.GetService<MyBackgroundServiceHere>(); provider.StartAsync(); provider.StopAsync
这是我在后台服务StartAsync中的代码
public Task StartAsync(CancellationToken cancellationToken) { _logger.LogDebug("Leaderboard minute ranking updates is starting"); Task.Run(async () => { while (!cancellationToken.IsCancellationRequested) { _logger.LogDebug("Leaderboard minute ranking updates is dequeueing"); await DequeueRandomCustomers(); _logger.LogDebug("Leaderboard minute ranking updates is enqueueing"); await EnqueueRandomCustomers(); _logger.LogDebug("Leaderboard minute ranking updates thread is now sleeping"); //sleep for 1 minute await Task.Delay(new TimeSpan(0, 0, 10)); } }); return Task.CompletedTask; }
我对注册后台服务有一些问题感到困惑,因为我看到后台服务启动了,但从长远来看,它突然停止了,我已经摆脱了后台服务中的那些Thread.Sleep(),希望您能为您提供帮助提前。
嗨,我最初使用IHostedService为我的后台服务运行一个长任务时遇到问题,但确实可以正常工作,但从长远来看,后台服务突然停止了……
appsettings.json
中设置服务的配置,将其配置为reloadOnChange: true
,然后使用IOptionsMonitor<>
访问appsettings.json
中的当前值。并将该设置用作托管服务的StartAsync
方法中已启动任务的取消。并且您需要监听OnChange
的IOptionsMonitor<>
事件以重新启动服务。