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

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

相关推荐
泛凡(Linyongui)12 小时前
基于 CW32L010 的智能厨卫调温旋钮方案--低成本 EC21 编码旋钮全解析
单片机·嵌入式硬件·c#
暴走约伯14 小时前
【VFX工具链源码拆解 02】告别机械劳动(上):一键统改百个子粒子颜色与批量重命名
3d·unity·c#·材质
信息安全失业大专人员15 小时前
每日了解一个智能体-WorkBuddy
开发语言·ai·c#·智能体
呆呆敲代码的小Y16 小时前
【实战精选面试题】C# 面试题详细解答,按难易程度排序
android·java·游戏·c#·游戏开发·unity面试题·c#面试题
淡海水17 小时前
09-01-内存-Unity资源生命周期全景
unity·c#·游戏引擎·.netcore·gc
椒颜皮皮虾྅20 小时前
让 C# 读懂整张图:DeploySharp 驱动 PaddleOCR v4/v5/v6,打通 OCR 全流程
开发语言·人工智能·深度学习·学习·c#·ocr·cuda
昂好的day20 小时前
C# 同步异步与多线程:Thread / Task / 线程池一次讲透(上篇)
开发语言·windows·c#
吃一碗粉只付一碗钱1 天前
12-给SPA友好的401和403响应
c#·状态模式
caimouse1 天前
MonoDevelop 编译用户应用程序时调用的是哪个编译器
c#
will_net2 天前
apollo 站点部署&C#接入
开发语言·c#·apollo