【问题标题】:Service not calling OnShutdown() when windows shuts downWindows 关闭时服务未调用 OnShutdown()
【发布时间】:2019-06-25 08:16:01
【问题描述】:

我有 .net 核心控制台应用程序,它作为 Windows 服务托管。
如果用户注销/关闭计算机,我想捕获一个事件。

我已经找到了在 .net 框架中捕获此事件的方法 (here & here)。
但我不知道如何在 .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-core windows-services asp.net-core-2.2


    【解决方案1】:

    根据aspisof.net,您应该可以使用 SessionEnding API。这是因为它被列为在 windows Compatibility Pack 中公开 - 在 NuGet here 上可用。

    docs.microsoft.com 上的This article 展示了如何将其包含在 .NET Core 应用程序中。


    tl;dr

    1. 添加 NuGet 包
    2. 仅目标 Windows

    需要注意的一点:这最初旨在作为将 Windows 特定 .NET 代码移植到 .NET Core 的临时修复程序。

    实现仅限 Windows 的功能更被接受的方法是将尽可能多的代码移至.NET Standard libraries,并在为该平台构建时使用conditional compilation directives 包含平台特定的代码。

    【讨论】:

    • 感谢您的帮助。但是控制台应用程序(作为 Windows 服务托管)不会引发 SessionEnding 事件。在 Windows 服务中,除非使用隐藏表单或手动启动消息泵,否则不会引发此事件。实际问题是在 .NET Core 2.2 Assembly System.Windows.Forms 中缺少提到的here
    • 我已经更新了我的问题,你能帮帮我吗?
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多