2017-09-11 50 views
1

我是Azure Webjobs的新手。我試圖實現GraceFul關機。同時使用WebJobsShutdownWatcher類。C在Azure Webjob中的GraceFul ShutDown#

Public static void Main() 
{ 
    try 
    { 
     var config = new JobHostConfiguration(); 

     if (config.IsDevelopment) 
     { 
      config.UseDevelopmentSettings(); 
     } 

     var watcher = new WebJobsShutdownWatcher(); 
     Task.Run(() => 
     { 
      bool isCancelled = false; 
      while (!isCancelled) 
      { 
       if (watcher.Token.IsCancellationRequested) 
       { 
        Console.WriteLine("WebJob cancellation Token Requested!"); 
        isCancelled = true; 
       } 
      } 
     }, watcher.Token).Wait(); 

     var host = new JobHost(); 
     The following code ensures that the WebJob will be running continuously 
     host.RunAndBlock(); 
    } 
    catch (Exception) 
    { 
     Console.WriteLine("Error"); 
    } 
} 

要實現GraceFul ShutDown,我已停止Webjob並再次託管在天藍色。 在Azure上託管之後,隊列未獲得觸發器。當我調試代碼時,控制停止在WebJobsShutdownWatcher類。 我做了什麼錯了?

+0

您應該刪除您Task.Run等待()()否則代碼後從不打。 – Thomas

+0

你也可以看到這些帖子:https://stackoverflow.com/questions/35166010/azure-triggered-webjob-detecting-when-webjob-stops/ https://stackoverflow.com/questions/36760241/intercept-azure- function-host-shutdown-flush-application-insights-telemetryclie – Thomas

回答

2

正如Thomas所說,你的代碼有問題。

由於WebJobsShutdownWatcher類將繼續監視webjobs狀態,並且您使用wait方法等待WebJobsShutdownWatcher類獲取取消標記,因此host.RunAndBlock方法從不會被命中。

您可以刪除等待方法,代碼將工作正常。

在這裏我寫一個測試演示,它效果很好。

static void Main() 
    { 
     var config = new JobHostConfiguration(); 

     if (config.IsDevelopment) 
     { 
      config.UseDevelopmentSettings(); 
     } 

     var watcher = new WebJobsShutdownWatcher(); 



     Task.Run(() => 
     { 
      bool isCancelled = false; 
      while (!isCancelled) 
      { 
       if (watcher.Token.IsCancellationRequested) 
       { 
        Console.WriteLine("WebJob cancellation Token Requested!"); 
        isCancelled = true; 
       } 
      } 
     }, watcher.Token); 


     var host = new JobHost(config); 
     // The following code ensures that the WebJob will be running continuously 
     host.RunAndBlock(); 
    } 

enter image description here

+1

這僅用於通知我們Webjobs正在關閉?我們可以暫停Webjob的Shutdown,以便當前的工作可以在Webjob關閉後完成。 @Brando Zhang – SaTyA