【发布时间】: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