首页 > 解决方案 > Azure 上的 .Net Core 后台服务作为 WebJob 不调用 StopAsync

问题描述

我们有一个用 .Net Framework 编写的 Windows 服务,我们正在考虑移植到 .NET Core 和一个在 Azure 中运行的 BackgroundService。

我创建了一个样板 BackgroundService(工作人员服务项目模板)并将其作为 WebJob 部署到 Azure。

我们的服务在运行时保持与第 3 方 API 的连接,因此我需要确保在 WebJob 停止时正常关闭此连接;是否停止 Azure 中的 WebJob,通过 VS 发布更新版本。

但是我发现,当我在 Azure 中停止 WebJob 时,不会调用 StopAsync 方法;相反,我在日志中得到一个 ThreadAborted 异常。

作为 WebJob 运行时,是否有一种最佳实践方式可以优雅地关闭 BackgroundService?

或者我什至应该为此使用其他一些 Azure 工具集?

标签: c#.netazureazure-webjobsbackground-service

解决方案


如果这对任何人有帮助,我解决了这个问题,感谢指针@HarshithaVeeramalla-MT,在https://blog.amitapple.com/post/2014/05/webjobs-graceful-shutdown/#.YZNWEk5By3Ahttps://github .com/projectkudu/kudu/wiki/WebJobs#graceful-shutdown

    private string _shutdownFile;

public Worker(ILogger<Worker> logger)
{            
    _logger = logger;

    _shutdownFile = Environment.GetEnvironmentVariable("WEBJOBS_SHUTDOWN_FILE");

    if (!string.IsNullOrEmpty(_shutdownFile))
    {
        _logger.LogInformation($"WebJob WEBJOBS_SHUTDOWN_FILE Environment Variable: {_shutdownFile}");

        var fileSystemWatcher = new FileSystemWatcher(Path.GetDirectoryName(_shutdownFile));
        fileSystemWatcher.Created += OnChanged;
        fileSystemWatcher.Changed += OnChanged;
        fileSystemWatcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.FileName | NotifyFilters.LastWrite;
        fileSystemWatcher.IncludeSubdirectories = false;
        fileSystemWatcher.EnableRaisingEvents = true;
    }
    else
    {
        _logger.LogWarning($"WebJob WEBJOBS_SHUTDOWN_FILE Environment Variable not found");
    }            
}

private void OnChanged(object sender, FileSystemEventArgs e)
{
    _logger.LogInformation($"Filechanged: {e.FullPath}");
    _logger.LogInformation($"WebShutDownFile: {_shutdownFile}");

    _logger.LogInformation($"FileName: {Path.GetFileName(_shutdownFile)}");

    if (e.FullPath.IndexOf(Path.GetFileName(_shutdownFile), StringComparison.OrdinalIgnoreCase) >= 0)
    {
        // Found the file mark this WebJob as finished
        _logger.LogInformation($"***WebJob shutdown file found - shutting down service***");
    }
}

推荐阅读