c# - 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 工具集?
解决方案
如果这对任何人有帮助,我解决了这个问题,感谢指针@HarshithaVeeramalla-MT,在https://blog.amitapple.com/post/2014/05/webjobs-graceful-shutdown/#.YZNWEk5By3A和https://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***");
}
}
推荐阅读
- python - 根据对外部变量的检查来筛选列表的更快方法?
- python-3.x - ValueError:Series 的真值不明确。熊猫
- python - win32com 尝试打开 Access 数据库并使用 python 运行宏,但始终打开只读模式
- c++ - 两个线程将相同的内容写入同一个文件是否安全?
- php - Laravel 动态下拉获取数据问题
- c# - EF Core - 从字符串转换日期和/或时间时转换失败
- javascript - 错误消息“DevTools 无法加载 SourceMap:无法加载 chrome-extension://... 的内容”
- c# - Xml 反序列化在它应该为空时给出意外的默认值
- javascript - AWS Amplify 推送是否会打包整个 node_modules 文件夹?
- python-3.x - 我的算法的基准测试是否正确?