admin管理员组文章数量:1123144
This is perhaps a misunderstanding how a BackgroundService works in comparison to the older full framework Windows Service implementations, but when attempting to call host.StartAsync()
, after a call to host.StopAsync()
, StartAsync fails with the error: System.OperationCanceledException: 'The operation was canceled.'
Program.cs
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services => {
services.AddHostedService<TestWorker>();
})
.Build();
host.RunAsync();
while (true) {
Thread.Sleep(5000);
await host.StopAsync();
Thread.Sleep(5000);
await host.StartAsync();
}
TestWorker.cs
public class TestWorker : BackgroundService {
private readonly ILogger<TestWorker> _logger;
public TestWorker(ILogger<TestWorker> logger) {
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellationRequested) {
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
Can someone explain why this is, and what the proper way to programmatically start a BackgroundService is after it as been programmatically stopped?
本文标签: cRestarting a basic NET BackgroundService fails with SystemOperationCancelledExceptionStack Overflow
版权声明:本文标题:c# - Restarting a basic .NET BackgroundService fails with System.OperationCancelledException - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736550176a1944500.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论