首页 > 解决方案 > 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 方法。

标签: asp.net-corewindows-servicesasp.net-core-2.2

解决方案


按照设计,dotnet 核心对特定于平台的东西并不“友好”(在我看来,比如听注销事件)。

此处描述了我在 Windows 托管服务之一中使用的解决方案。

当应用程序域在关闭时被操作系统强制关闭时 - 存在使用 AppDomain 事件处理程序的空间。


推荐阅读