Azure服务结构如何在完成时重新运行RunAsync方法?

问题描述:

我有一个运行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); 
        } 
       } 

      }    
     } 
    } 
+0

我应该补充一点,当Service Fabric信号取消时,PollDatabase()中没有发生异常 – puri

+0

有一个'CloseAsync',但是'RunAsync'获取'CancellationToken'和'CloseAsync'这个事实令人困惑。你为什么需要两个? –

你可以有轮询方法的返回Task<T>,而不是Task?您可以将理由返回到您选择的对象中。

https://blog.stephencleary.com/2012/02/async-and-await.html

+0

我实际上需要知道为什么Service Fabric需要关闭此服务实例。这不会因池化方法引发异常而发生。 – puri

一旦服务织物决定正常从RunAsync方法返回,我怎么能再次运行我的查询程序?

据我所知,一旦它返回,RunAsync将被再次调用。 在Reliable services lifecycle overview上,您可以阅读以下内容。

对于有状态的可靠服务如果服务从主服务器降级后升级为主服务器,则会再次调用RunAsync()。

您还可以在那里阅读正在降级和升级的主副本的生命周期,其中不包括OnCloseAsync。

我该如何确定为什么Service Fabric发信号通知取消令牌?

恐怕你需要搜索抛出的异常。请注意,我不确定这个答案,这只是我的怀疑。