使用Topshelf部署window后台服务(C#)

使用ServiceBase的方式部署window后台服务很不方便,不方便调试开发,但使用Topshelf,安装服务简单,卸载服务简单,调试简单

测试环境:

visual studio 2022

win11

测试步骤如下:

1 新建名为DataSmartAgentService的.net framework控制台项目,.net framework选择.net framework 4.7,并新建服务类WindowService并编辑如下:

cs 复制代码
 public class WindowService
 {
     public bool StartService() 
     {
         string startTip = "service start...";
         Console.WriteLine(startTip);
         LogManager.GetInstance().WriteDebugLog(startTip);
         return true;
     }

     public bool StopService() 
     {
         string stopTip = "service stop..."; 
         Console.WriteLine(stopTip);
         LogManager.GetInstance().WriteDebugLog(stopTip);
         return true;
     }
 }

2 利用nuget安装Topshelf,版本选择4.3.0,如下图:

3 在主程序编写代码如下:

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Topshelf;

namespace DataSmartAgentService
{
    internal class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.Service<WindowService>(s =>
                {
                    s.ConstructUsing(name => new WindowService());
                    s.WhenStarted(tc => tc.StartService()); 
                    s.WhenStopped(tc => tc.StopService()); 
                });
                x.RunAsLocalSystem();
                x.StartAutomatically();
                x.SetServiceName("OPASDataSmartAgentService");
                x.SetDisplayName("OPASDataSmartAgentService");
                x.SetDescription("This is OPASDataSmartAgentService.");
            });
        }
    }
}

4 安装window后台服务

利用管理员打开cmd,然后切换到运行程序的目录

然后输入命令:

cs 复制代码
运行程序名称.exe  install

这里是DataSmartAgentService.exe install,如下图:

可以看到后台服务已经安装成功了,如下图:

5 有安装,肯定就有卸载,卸载也是很简单

利用管理员打开cmd,然后切换到运行程序的目录

然后输入命令:

cs 复制代码
运行程序名称.exe  uninstall

这里是DataSmartAgentService.exe uninstall

好了,本地的内容到此结束

相关推荐
Porco.w4 小时前
C#与三菱PLC FX5U通信
网络·c#
E_ICEBLUE6 小时前
PPT 批量转图片:在 Web 预览中实现翻页效果(C#/VB.NET)
c#·powerpoint·svg
JQLvopkk7 小时前
C# 轻量级工业温湿度监控系统(含数据库与源码)
开发语言·数据库·c#
wxin_VXbishe10 小时前
C#(asp.net)学员竞赛信息管理系统-计算机毕业设计源码28790
java·vue.js·spring boot·spring·django·c#·php
bugcome_com1 天前
零基础入门C#:一篇搞懂核心知识点
c#
程序员敲代码吗1 天前
如何通过命令行启动COMSOL的参数化、批处理和集群扫描
java·c#·bash
缺点内向1 天前
C#: 告别繁琐!轻松移除Word文档中的文本与图片水印
c#·自动化·word·.net
喵叔哟1 天前
06-ASPNETCore-WebAPI开发
服务器·后端·c#
2501_930707781 天前
使用 C# .NET 从 PowerPoint 演示文稿中提取背景图片
c#·powerpoint·.net
初级代码游戏1 天前
套路化编程 C# winform 自适应缩放布局
开发语言·c#·winform·自动布局·自动缩放