互联网技术 · 2024年2月20日

.NET Core使用Topshelf创建Windows服务的全过程记录

这篇文章主要给大家介绍了关于.NET Core使用Topshelf方式创建Windows服务的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

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

安装

Install-Package Topshelf

.NET Core使用Topshelf方式创建Windows服务的全过程记录

代码

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();
   }
  );
  }
 }
}

部署服务

.NET Core使用Topshelf方式创建Windows服务的全过程记录

ConsoleApp2222.exe install

ConsoleApp2222.exe start

调试服务

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

.NET Core使用Topshelf方式创建Windows服务的全过程记录

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

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

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

.NET Core使用Topshelf方式创建Windows服务的全过程记录

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

参考文档

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

https://github.com/Topshelf/Topshelf

http://topshelf-project.com/

总结

到此这篇关于.NET Core使用Topshelf方式创建Windows服务的文章就介绍到这了,更多相关.NET Core用Topshelf创建Windows服务内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:脚本之家

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.

登录免费注册