使用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

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

相关推荐
real向往1 天前
Ubuntu NVIDIA显卡驱动安装
ubuntu·安装·显卡驱动
八苦1 天前
如何用c# 做 mcp/ChatGPT app
c#·mcp
人工智能AI技术1 天前
DeskClaw Windows上线|C#开发AI桌面助手,轻量内核源码解析
人工智能·c#
似水明俊德1 天前
04-C#.Net-委托和事件-面试题
java·开发语言·面试·c#·.net
程序员老乔1 天前
Java 新纪元 — JDK 25 + Spring Boot 4 全栈实战(二):Valhalla落地,值类型如何让电商DTO内存占用暴跌
java·spring boot·c#
祝大家百事可乐1 天前
嵌入式——02 数据结构
c++·c#·硬件工程
我是唐青枫1 天前
深入理解 C#.NET TaskScheduler:为什么大量使用 Work-Stealing
c#·.net
唯情于酒1 天前
net core web api 使用log4net
c#·.net core
SunnyDays10111 天前
C# 实战:快速查找并高亮 Word 文档中的文字(普通查找 + 正则表达式)
开发语言·c#
人工智能AI技术1 天前
Qwen3.5-Plus登顶|C#集成通义千问,高并发服务实战优化
人工智能·c#