C#之Windows服务开发笔记
1,服务程序框架需和发布工具InstallUtil版本一致;
2,InstallUtil一般随VisualStudio/dotNetFramework安装而安装,在C:\Windows\Microsoft.NET\Framework路劲的对应版本号目录下;
3,一个Windows服务程序可以加载多个服务,在Main方法中添加即可;
1 2 3 4 5 6 7 | ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1(), new Service2() }; ServiceBase.Run(ServicesToRun); |
4,Windows服务程序需添加安装程序[ProjectInstaller],可据服务个数创建相应的安装服务对象,并自定义名称,如:
1 2 | this .serviceInstaller1.Description = "TEST SERVICE" ; this .serviceInstaller1.ServiceName = "Service1" ; |
5,安装过后的服务可根据设定的ServiceName去Windows服务中查找;
6,使用InstallUtil安装服务程序(exe)时,会要求输入账号密码,测试时可默认为:
1 2 3 | this .serviceProcessInstaller1.Password = null ; this .serviceProcessInstaller1.Username = null ; this .serviceProcessInstaller1.Account = ServiceAccount.LocalService; //添加这行 |
7,业务Service逻辑重写OnStart方法(与一般console程序无异);
8,安装与卸载脚本(批处理文件)
1 2 3 4 5 6 7 8 9 10 | ##安装 %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil D:\BackServices\WindowsService1.exe Net Start Service1 sc config Service1 start= auto ##pause##调试 ##卸载 Net Stop Service1 %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil /u D:\BackServices\WindowsService1.exe ##pause |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合终身会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步