重新启动失败的背景服务
因此,我拥有这样的背景服务,看起来像这样。
public class MyBackgroundService: BackgroundService
{
public MyBackgroundService(){}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
new Thread(() => new MessageHandler().Process(stoppingToken).Start();
return Task.CompletedTask;
}
}
如果过程方法会引发例外,那么无论如何是否可以尝试重新启动 背景服务或创建新的MessageHandler并运行过程?
编辑,反馈和谷歌搜索后,我想这样的事情
protected override Task ExecuteAsync(CancellationToken cancellationToken)
{
Task.Run(() => RunConsumer(cancellationToken)).Start();
return Task.CompletedTask;
}
private void RunConsumer(CancellationToken cancellationToken)
{
while (true)
{
using var scope = _serviceScopeFactory.CreateScope();
var myConsumer = scope.ServiceProvider.GetRequiredService<IMyConsumer>();
Task.Run(() => { new Thread(() => myConsumer.Start()).Start(); })
.ContinueWith(t =>
{
if (t.IsFaulted) {/* Log t.Exception and retry x times */}
if (t.IsCompleted) {/* Should not not happen in my case */}
});
}
}
So I have this background service that looks something like this.
public class MyBackgroundService: BackgroundService
{
public MyBackgroundService(){}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
new Thread(() => new MessageHandler().Process(stoppingToken).Start();
return Task.CompletedTask;
}
}
If the Process-method would throw an Exception, is there anyway to try to restart
the background service or create a new MessageHandler and run Process?
EDIT, After feedback and googling, Im thinking something like this
protected override Task ExecuteAsync(CancellationToken cancellationToken)
{
Task.Run(() => RunConsumer(cancellationToken)).Start();
return Task.CompletedTask;
}
private void RunConsumer(CancellationToken cancellationToken)
{
while (true)
{
using var scope = _serviceScopeFactory.CreateScope();
var myConsumer = scope.ServiceProvider.GetRequiredService<IMyConsumer>();
Task.Run(() => { new Thread(() => myConsumer.Start()).Start(); })
.ContinueWith(t =>
{
if (t.IsFaulted) {/* Log t.Exception and retry x times */}
if (t.IsCompleted) {/* Should not not happen in my case */}
});
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以像这样编写主循环:
关键点是
concellationToken.iscancellationRequested
,该服务将在请求时停止,例如,当该过程优雅地结束时,task.delay
确保该过程不会经常重新启动。在
runconsumer
中,您可以使用它通常最好使用异步/等待,因此您不必手动进行延续和错误检查。
You can write main loop like this:
The key points is
cancellationToken.IsCancellationRequested
, the service will be stopped when it is requested, e.g. when the process is ending gracefully,Task.Delay
ensures that the process will not be restarted too often.In
RunConsumer
you can just useIt is usually better to use async/await so you don't have to do the continuation and error-checking manually.