当前位置: 移动技术网 > IT编程>开发语言>.net > .NET Core使用Topshelf方式创建Windows服务的全过程记录

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

2020年11月04日  | 移动技术网IT编程  | 我要评论
前言topshelf是一个.net standard库,它消除了在.net framework和.net core中创建windows服务的那些麻烦。安装install-package topshel

前言

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://topshelf-project.com/

总结

到此这篇关于.net core使用topshelf方式创建windows服务的文章就介绍到这了,更多相关.net core用topshelf创建windows服务内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网