我有一個運行RunAsync方法內的後臺進程的無狀態服務。Azure服務結構如何在完成時重新運行RunAsync方法?
此後臺進程必須永久運行。它所做的是無關的,但它實際上每60秒輪詢一次數據庫。
與Worker角色或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);
}
}
}
}
}
我應該補充一點,當Service Fabric信號取消時,PollDatabase()中沒有發生異常 – puri
有一個'CloseAsync',但是'RunAsync'獲取'CancellationToken'和'CloseAsync'這個事實令人困惑。你爲什麼需要兩個? –