我有一个在 RunAsync 方法中运行后台进程的无状态服务。
这个后台进程必须永远运行。它的作用无关紧要,但它实际上每 60 秒轮询一次数据库。
与辅助角色或 WebJob 不同,Service Fabric 服务中的 RunAsync 方法可以运行到完成,并且服务实例将保持运行。
当 Service Fabric 向传递给 RunAsync 的取消令牌发出信号时,已观察到会发生这种情况。
一旦 Service Fabric 决定从 RunAsync 方法正常返回,如何再次重新运行轮询例程?
以及如何确定 Service Fabric 首先发出取消令牌的原因?
我当前的解决方法是抛出异常,以便强制重新启动服务。
public class Stateless1 : StatelessService
{
protected override async Task RunAsync(CancellationToken cancellationToken)
{
try
{
await Start(cancellationToken);
}
catch(OperationCanceledException ex)
{
throw;
//If an OperationCanceledException escapes from
//RunAsync(CancellationToken) and Service Fabric runtime has requested
//cancellation by signaling cancellationToken passed to
//RunAsync(CancellationToken), Service Fabric runtime handles this exception and
//considers it as graceful completion of RunAsyn(CancellationToken).
}
catch(Exception ex)
{
// log error
throw;
// force service to restart, If an exception of any other type escapes from
// RunAsync(CancellationToken) then the process that is hosting this service
// instance is brought down
}
}
private async Task Start(CancellationToken cancellationToken)
{
while(true)
{
cancellationToken.ThrowIfCancellationRequested(); // honour cancellation token
try
{
await PollDatabase();
}
catch(Exception ex)
{
// log error
throw;
}
finally
{
for (var i = 0; i < 12; i++)
{
cancellationToken.ThrowIfCancellationRequested(); // honour cancellation token
await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
}
}
}
}
}