asp.net-core - Windows 关闭时服务未调用 OnShutdown()
问题描述
我有 .net 核心控制台应用程序,它作为 Windows 服务托管。
如果用户注销/关闭计算机,我想捕捉一个事件。
我找到了在 .net 框架(此处和此处)中捕获此事件的方法。
但我不知道如何在 .net 核心中实现这一点。
要创建服务,我使用“ServiceBase”类。示例代码如下:
public class MyService : ServiceBase
{
readonly string LogPath = "D:\\TestAppService.txt";
#region Constructors
public MyService()
{
this.CanShutdown = true;
}
#endregion
#region Protected Functions
protected override void OnStart(string[] args)
{
//your code here
// call the base class so it has a chance
// to perform any work it needs to
base.OnStart(args);
}
protected override void OnStop()
{
//your code here
// Call the base class
base.OnStop();
}
protected override void OnShutdown()
{
using (StreamWriter sw = File.AppendText(LogPath))
{
sw.WriteLine("shutdown == true");
}
//your code here
base.OnShutdown();
}
#endregion
}
正在调用 OnStop 和 OnStart 方法。
但是当我关闭计算机时,不会调用我的 OnShutdown 方法。
解决方案
按照设计,dotnet 核心对特定于平台的东西并不“友好”(在我看来,比如听注销事件)。
此处描述了我在 Windows 托管服务之一中使用的解决方案。
当应用程序域在关闭时被操作系统强制关闭时 - 存在使用 AppDomain 事件处理程序的空间。
推荐阅读
- oracle-apex - Oracle apex 表格形式刷新问题
- python - 如何在python中识别函数和模块化代码?
- testng - 即使 testng 类中的方法抛出异常, ITestResult 也会返回状态成功
- javascript - 检查对象嵌套属性是否存在并返回其值
- resources - 当 URL 未出现在源代码中时,如何避免错误请求?
- html - 如何旋转外部div而不是内部内容
- php - 如何修复 'Illuminate \ Database \ Eloquent \ MassAssignmentException' 上的 _token 错误
- reactjs - React- Webpack 缩小代码并在开发环境中创建包。我想要 dev 中的所有未捆绑的文件,以便我可以调试
- java - ListView 不使用自定义视图更新大小
- xml - XML 文件输出失败