C#之Windows服务开发笔记

1,服务程序框架需和发布工具InstallUtil版本一致;

2,InstallUtil一般随VisualStudio/dotNetFramework安装而安装,在C:\Windows\Microsoft.NET\Framework路劲的对应版本号目录下;

3,一个Windows服务程序可以加载多个服务,在Main方法中添加即可;

ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
 {
    new Service1(),
    new Service2()
};
ServiceBase.Run(ServicesToRun);

4,Windows服务程序需添加安装程序[ProjectInstaller],可据服务个数创建相应的安装服务对象,并自定义名称,如:

this.serviceInstaller1.Description = "TEST SERVICE";
this.serviceInstaller1.ServiceName = "Service1";

5,安装过后的服务可根据设定的ServiceName去Windows服务中查找;

6,使用InstallUtil安装服务程序(exe)时,会要求输入账号密码,测试时可默认为:

this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
this.serviceProcessInstaller1.Account = ServiceAccount.LocalService;//添加这行

7,业务Service逻辑重写OnStart方法(与一般console程序无异);

8,安装与卸载脚本(批处理文件)

##安装
%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

 

posted @ 2019-11-06 14:25  ShawSir  阅读(263)  评论(0编辑  收藏  举报