使用C#创建Windows服务
一、开发环境
操作系统:Windows 10 X64
开发环境:VS2015
编程语言:C#
.NET版本:.NET Framework 4.0
目标平台:X86
二、创建Windows Service
1、新建一个Windows Service,并将项目名称改为“MyWindowsService”,如下图所示:
2、在解决方案资源管理器内将Service1.cs改为MyService1.cs后并点击“查看代码”图标按钮进入代码编辑器界面,如下图所示:
3、在代码编辑器内如入以下代码,如下所示:
using System; using System.ServiceProcess; using System.IO; namespace MyWindowsService { public partial class MyService : ServiceBase { public MyService() { InitializeComponent(); } string filePath = @"D:\MyServiceLog.txt"; protected override void OnStart(string[] args) { using (FileStream stream = new FileStream(filePath,FileMode.Append)) using (StreamWriter writer = new StreamWriter(stream)) { writer.WriteLine($"{DateTime.Now},服务启动!"); } } protected override void OnStop() { using (FileStream stream = new FileStream(filePath, FileMode.Append)) using (StreamWriter writer = new StreamWriter(stream)) { writer.WriteLine($"{DateTime.Now},服务停止!"); } } } }
4、双击项目“MyWindowsService”进入“MyService”设计界面,在空白位置右击鼠标弹出上下文菜单,选中“添加安装程序”,如下图所示:
5、此时软件会生成两个组件,分别为“serviceInstaller1”及“serviceProcessInstaller1”,如下图所示:
6、点击“serviceInstaller1”,在“属性”窗体将ServiceName改为MyService,Description改为我的服务,StartType保持为Manual,如下图所示:
7、点击“serviceProcessInstaller1”,在“属性”窗体将Account改为LocalSystem(服务属性系统级别),如下图所示:
8、鼠标右键点击项目“MyWindowsService”,在弹出的上下文菜单中选择“生成”按钮,如下图所示:
9、至此,Windows服务已经创建完毕。
三、创建安装、启动、停止、卸载服务的Windows窗体
1、在同一个解决方案里新建一个Windows Form项目,并命名为WindowsServiceClient,如下图所示:
2、将该项目设置为启动项目,并在窗体内添加四个按钮,分别为安装服务、启动服务、停止服务及卸载服务,如下图所示:
3、按下F7进入代码编辑界面,引用“System.ServiceProcess”及“System.Configuration.Install”,并输入如下代码:
using System; using System.Collections; using System.Windows.Forms; using System.ServiceProcess; using System.Configuration.Install; namespace WindowsServiceClient { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string serviceFilePath = $"{Application.StartupPath}\\MyWindowsService.exe"; string serviceName = "MyService"; //事件:安装服务 private void button1_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceName); this.InstallService(serviceFilePath); } //事件:启动服务 private void button2_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName); } //事件:停止服务 private void button4_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName); } //事件:卸载服务 private void button3_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) { this.ServiceStop(serviceName); this.UninstallService(serviceFilePath); } } //判断服务是否存在 private bool IsServiceExisted(string serviceName) { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController sc in services) { if (sc.ServiceName.ToLower() == serviceName.ToLower()) { return true; } } return false; } //安装服务 private void InstallService(string serviceFilePath) { using (AssemblyInstaller installer = new AssemblyInstaller()) { installer.UseNewContext = true; installer.Path = serviceFilePath; IDictionary savedState = new Hashtable(); installer.Install(savedState); installer.Commit(savedState); } } //卸载服务 private void UninstallService(string serviceFilePath) { using (AssemblyInstaller installer = new AssemblyInstaller()) { installer.UseNewContext = true; installer.Path = serviceFilePath; installer.Uninstall(null); } } //启动服务 private void ServiceStart(string serviceName) { using (ServiceController control = new ServiceController(serviceName)) { if (control.Status == ServiceControllerStatus.Stopped) { control.Start(); } } } //停止服务 private void ServiceStop(string serviceName) { using (ServiceController control = new ServiceController(serviceName)) { if (control.Status == ServiceControllerStatus.Running) { control.Stop(); } } } } }
4、为了后续调试服务及安装卸载服务的需要,将已生成的MyWindowsService.exe引用到本Windows窗体,如下图所示:
5、由于需要安装服务,故需要使用UAC中Administrator的权限,鼠标右击项目“WindowsServiceClient”,在弹出的上下文菜单中选择“添加”->“新建项”,在弹出的选择窗体中选择“应用程序清单文件”并单击确定,如下图所示:
6、打开该文件,并将<requestedExecutionLevel level="asInvoker" uiAccess="false" />改为<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />,如下图所示:
7、IDE启动后,将会弹出如下所示的窗体(有的系统因UAC配置有可能不显示),需要用管理员权限打开:
8、重新打开后,在IDE运行WindowsServiceClient项目;
9、使用WIN+R的方式打开运行窗体,并在窗体内输入services.msc后打开服务,如下图所示:
10、点击窗体内的“安装服务”按钮,将会在服务中出现MyService,如下图所示:
11、点击“运行服务”按钮,将启动并运行服务,如下所示:
12、点击“停止服务”按钮,将会停止运行服务,如下图所示:
13、点击“卸载服务”按钮,将会从服务中删除MyService服务。
14、以上启动及停止服务将会写入D:\MyServiceLog.txt,内容如下所示:
源代码下载:
或:
https://download.****.net/download/lixiaoer757/10441930
补充:如何调试服务
1、要调试服务,其实很简单,如需将服务附加进程到需要调试的项目里面即可,假如要调试刚才建的服务,现在OnStop事件里设置断点,如下所示:
2、启动“WindowsServiceClient”项目,在“调试”菜单中选择“附件到进程”(服务必须事先安装),如下所示:
3、找到“MyWindowsService.exe”,点击“附加”按钮,如下图所示:
4、点击“停止服务”按钮,程序将会在设置断点的地方中断,如下图所示:
出处:http://www.cnblogs.com/cncc/p/7170951.html
作者:CNXY
Github:https://www.github.com/cnxy出处:http://www.cnc6.cn
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果文中有什么错误,欢迎指出,谢谢!
二、window Service
windows服务应用程序是一种长期运行在操作系统后台的程序,它对于服务器环境特别适合,它没有用户界面,不会产生任何可视输出,任何用户输出都回被写进windows事件日志。
计算机启动时,服务会自动开始运行,他们不要用户一定登陆才运行。
可以通过选择菜单“开始”-〉“控制面板”-〉“管理工具”-〉“服务”来查看现有系统中的服务,如下图:
创建一个windows服务
切换到代码视图修改.
using System; using System.IO; using System.ServiceProcess; namespace WindowsServiceTest { public partial class hjpServiceTest : ServiceBase { //定时器 System.Timers.Timer t = null; public hjpServiceTest() { InitializeComponent(); //启用暂停恢复 base.CanPauseAndContinue = true; //每5秒执行一次 t = new System.Timers.Timer(5000); //设置是执行一次(false)还是一直执行(true); t.AutoReset = true; //是否执行System.Timers.Timer.Elapsed事件; t.Enabled = true; //到达时间的时候执行事件(theout方法); t.Elapsed += new System.Timers.ElapsedEventHandler(theout); } //启动服务执行 protected override void OnStart(string[] args) { string state = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "启动"; WriteLog(state); } //停止服务执行 protected override void OnStop() { string state = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "停止"; WriteLog(state); } //恢复服务执行 protected override void OnContinue() { string state = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "继续"; WriteLog(state); t.Start(); } //暂停服务执行 protected override void OnPause() { string state = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "暂停"; WriteLog(state); t.Stop(); } public void WriteLog(string str) { using (StreamWriter sw = File.AppendText(@"d:\service.txt")) { sw.WriteLine(str); sw.Flush(); } } public void theout(object source, System.Timers.ElapsedEventArgs e) { WriteLog("theout:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")); } } }
解释:OnStart和OnStop分别是服务器启动和停止后,所发生的事件操作方法.定义了一个定时器,每隔5秒执行一次(theout方法),因为暂停恢复功能默认是不启用的,需要设置CanPauseAndContinue属性启用此功能,同时重写OnStop和OnContinue方法,添加自己的逻辑代码.
将服务程序hjpServiceTest.cs 切换到视图模式,用鼠标右键单击设计视图选择“添加安装程序”选项,此后在项目中自动增加了一个ProjectInstaller.cs,
如下图
打开ProjectInstaller,修改serviceInstaller1组件属性
Description= 我的服务备注 服务备注说明
DisplayName=我的服务 服务友好名字
ServiceName=hjpServiceTest 安装服务器名字
StartType=Automatic 服务类型
ü Manual 服务安装后,必须手动启动。
ü Automatic 每次计算机重新启动时,服务都会自动启动。
ü Disabled 服务无法启动。
并设计serviceProcessInstaller1的属性Account=LocalSystem
运行编译,一个简单的windows服务已经开发完成.
安装window服务
安装命令:InstallUtil.exe WindowsServiceTest.exe
InstallUtil存在路径为:C:\WINDOWS\Microsoft.NET\Framework\.NET版本号
复制C:\WINDOWS\Microsoft.Net\Framework\版本号 路径中的InstallUtil.exe 到bin/debug或bin/release文件夹中,在命令行窗口中直接运行命令
InstallUtil.exe WindowsServiceTest.exe,在系统中注册这个服务,使它建立一个合适的注册项,如下图:
然后再window服务列表中,启动hjpServiceTest服务
卸载window 服务
命令:InstallUtil.exe WindowsServiceTest.exe /u
如果修改这个服务,但是路径没有变化的话是不需要重新注册服务的,直接停止服务,然后用新的文件覆盖原来的文件即可,如果路径发生变化,应该先卸载这个服务,然后重新安装这个服务。
------------------------------------------------------------------------------------------------------
Window服务应用程序体系结构
.net framework对windows服务提供了更多的支持,在命名空间System.ServiceProcess下.
包括类如下:
ServiceBase 所有Window服务的基类
ServiceController 该类的一个实例代表一个具体的windows服务
ServiceControllerPermission 用于控制ServiceController的使用权限
ServiceInstaller 用于执行对windows服务的安装
ServiceProcessInstaller 用于执行对windows服务的安装,与上类的不同的是,该类可以代表一个可以执行的windows服务的进程.
ServiceBase类
ServiceBase方法:
方法 |
描述 |
Run() |
运行一个windows服务 |
OnContinue() |
继续执行服务 |
OnCustomCommand() |
向windows服务发出自定指令 |
OnPause() |
暂停正在运行的windows服务 |
OnPowerEvent() |
当计算机的电源状态改变是调用 |
OnShutDown() |
当系统关闭条用OnStart()开始一个windows服务 |
OnStop() |
结束一个windows服务 |
ServiceBase属性:
属性 |
描述 |
AutoLog |
表示是否将开始,结束,暂停,继续等指令写入事件日志 |
CanHandlePowerEvent |
表示该服务是否支持电源事件 |
CanPauseAndContinue |
表示该服务是否支持暂停和继续功能 |
CanShutDown |
表示该服务是否支持关闭功能 |
CanStop |
表示该服务是否支持结构功能 |
EventLog |
应用程序的时间日志 |
ServiceName |
该服务名称 |
ServiceController类
服务控制类,用于控制windows服务的各种具体行为,它既可以控制本地的windows服务,有可以控制远程的windows服务。
ServiceControler的方法:
方法 |
描述 |
GetDivices() |
得到一台计算机上设备驱动器服务 |
GetServices() |
得到一台计算上的非设备驱动器服务 |
Close() |
用于断开服务连接,并且释放服务控制器所占用的资源 |
Continue() |
继续被暂停的服务 |
ExcuteCommand() |
对服务执行一条自定义命令 |
Pause() |
暂停服务 |
Refresh() |
对所有属性更新 |
Start() |
启动服务 |
Stop() |
停止服务 |
WaitForStatus() |
等待服务到达指定的状态 |
ServiceController属性
属性 | 描述 |
CanPauseAndContinue | 表示服务是否可以停止 |
CanShutDown | 表示服务在系统关闭时是否可以得到通知,CanStop表示服务器是否可以被停止 |
DependentServices | 表示与服务相关联的设备 |
DisplayName | 表示服务控制器所绑定的名称 |
MachineName | 表示服务所在的计算机名称 |
ServiceName | 表示绑定的服务名称 |
ServiceType | 表示控制器所引用的服务类型 |
ServicesDependedOn | 表示服务所依赖ude服务集合Status表示控制器所引用的服务状态 |
ServiceInstaller类
ServiceInstaller的属性
属性 | 描述 |
DisplayName | 显示名称 |
ServiceName | 表示服务名称,这个名称必须与Installer将要安装的windows服务名称相同 |
ServiceDependOn | 服务所要用到的其服务名称的一个数组 |
StartType | 表示所安装服务的启动特性,可以为Automatic,Manual或Disable,默认为Manual |
方法 | 事件 |
AfterInstaller() | 调用Install方法后发生 |
AfterRollback() | 调用Rollback后发生 |
AfterUninstall() | 调用Uninstall方法后发生 |
BeforeInstall() | 调用Install方法前发生 |
BeforeRollback() | 调用Rollback方法前发生 |
BeforeUninstall() | 调用Uninstall方法前发生 |
Committed() | 调用Commit方法后发生 |
Committing() | 调用Commit方法前发生 |
ServiceProcessInstaller类
用于安装ServiceBase继承的windows服务,它与一个可执行程序中的所有服务所做基本工作相同
ServiceProcessInstaller属性
属性 | 描述 |
Account | 运行服务的当前用户账号 |
HelpText | 在服务安装选项中给出的帮助信息 |
Password | 运行服务的当前账号密码 |
UserName | 运行服务的当前账号用户名 |
------------------------------------------------------------------------------------------------------------------------
Windows服务调试
vs打开MySerivceLog项目
在管理工具-〉服务里面启动MyServiceLog服务
单击vs的调试 -〉附加到进程,如下图
在"可用进程“列表中,选中你要调式的服务的可执行文件名
单击 ”附加“按钮,即可进入调试状态
在timer1_Elapsed方法里设置一个断点,然后等它执行,服务执行到该处时候会自动启动断点。