C# Azure Webjob 中的 GraceFul ShutDown

GraceFul ShutDown in Azure Webjob in C#

我是 Azure Webjobs 的新手。我试图实现 GraceFul Shutdown。使用 WebJobsShutdownWatcher Class.

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 上。 在 Azure 上托管后,队列未获得触发器。当我调试代码时,控件在 WebJobsShutdownWatcher Class 处停止。 我做错了什么?

正如 Thomas 所说,您的代码有问题。

由于 WebJobsShutdownWatcher class 将继续监视 webjobs 状态,并且您使用 wait 方法等待 WebJobsShutdownWatcher class 获取取消标记,因此永远不会命中 host.RunAndBlock 方法。

您可以删除 wait 方法,代码将运行良好。

这里我写了一个测试demo,效果不错

    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();
    }