2020-11-04

.NET Core 使用Topshelf方式创建Windows服务

Topshelf是一个.NET Standard库,它消除了在.NET Framework和.NET Core中创建Windows服务的那些麻烦。

安装

Install-Package Topshelf

代码

using System;using System.Collections.Generic;using System.Text;using Topshelf;namespace ConsoleApp2222{ public class LoggingService : ServiceControl {  private void Log(string logMessage)  {   Console.WriteLine(logMessage);  }  public bool Start(HostControl hostControl)  {   Log("Starting");   return true;  }  public bool Stop(HostControl hostControl)  {   Log("Stopping");   return true;  } }}

  

 

在Program.cs文件的Main方法中

1、服务的名称

2、服务是否自动启动

3、服务崩溃之后的重启时间

using System;using Topshelf;namespace ConsoleApp2222{ internal class Program {  private static void Main(string[] args)  {   HostFactory.Run(x =>   {    x.Service<LoggingService>();    x.EnableServiceRecovery(r => r.RestartService(TimeSpan.FromSeconds(10)));    x.SetServiceName("TestService");    x.StartAutomatically();   }  );  } }}

  

 

部署服务

  •  
ConsoleApp2222.exe install
  •  
ConsoleApp2222.exe start

调试服务

如果我们的服务代码已经在Visual Studio中打开了,我们就可以直接启动调试。Topshelf会模拟在控制台中启动服务。我们应该能在控制台中看到以下的消息。

这确实符合了我们的需求。它启动了我们的服务,并像真正的Windows服务一样在后台运行。我们可以像往常一样设置断点,基本上它遵循的流程和正常安装的服务一样。

我们可以通过ctrl+c, 来关闭我们的应用,但是在运行服务执行Stop方法之前,它是不能被关闭的,这使我们可以调试服务的关闭流程。与调试指令和配置标志相比,这要容易的多。

这里需要注意一个问题。如果你收到的以下内容的消息:

这意味着你尝试调试的服务实际上已经作为Windows服务被安装在系统中了,你需要停止(不需要卸载)这个正在运行的服务,才可以正常调试。

参考文档

https://topshelf.readthedocs.io/en/latest/configuration/config_api.html

https://github.com/Topshelf/Topshelf

原文转载:http://www.shaoqun.com/a/488065.html

stadium:https://www.ikjzd.com/w/2729

reverb:https://www.ikjzd.com/w/1273

徐家骏:https://www.ikjzd.com/w/1803


Topshelf是一个.NETStandard库,它消除了在.NETFramework和.NETCore中创建Windows服务的那些麻烦。安装Install-PackageTopshelf代码usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingTopshelf;namespaceConsoleApp2222{publ
prime:https://www.ikjzd.com/w/129
acca是什么:https://www.ikjzd.com/w/1370
深圳西冲海滩要门票吗?价格多少?:http://tour.shaoqun.com/a/39931.html
友家速递:https://www.ikjzd.com/w/1341
深圳有哪些口岸?:http://tour.shaoqun.com/a/1138.html

No comments:

Post a Comment