嗨,我在使用 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() 希望你能帮助提前谢谢.