Windows服务
windows服务应用程序是一种长期运行在操作系统后台的程序,它对于服务器环境特别适合,它没有用户界面,不会产生任何可视输出,任何用户输出都回被写进windows事件日志。计算机启动时,服务会自动开始运行,他们不要用户一定登陆才运行。可以通过选择菜单“开始”-〉“控制面板”-〉“管理工具”-〉“服务”来查看现有系统中的服务,如下图:
创建window 服务
切换到代码视图修改using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Diagnostics;using System.IO;using System.Linq;using System.ServiceProcess;using System.Text; namespace WindowsService1{ public partial class Service1 : ServiceBase { //定时器 System.Timers.Timer t = null; public Service1() { 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(@'e:\log.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方法,添加自己的逻辑代码.将服务程序Service1.cs 切换到视图模式,用鼠标右键单击设计视图选择“添加安装程序”选项,此后在项目中自动增加了一个ProjectInstaller.cs,如下图
打开ProjectInstaller,修改serviceInstaller1组件属性Description= 我的服务备注 服务备注说明DisplayName=我的服务 服务友好名字ServiceName=MyService 安装服务器名字StartType=Automatic 服务类型ü Manual 服务安装后,必须手动启动。ü Automatic 每次计算机重新启动时,服务都会自动启动。ü Disabled 服务无法启动。并设计serviceProcessInstaller1的属性Account=LocalSystem运行编译,一个简单的windows服务已经开发完成.ServiceInstaller1的属性设置如下:
serviceProcessInstaller1的属性设置如下:
安装window服务安装命令:InstallUtil.exe MyServiceLog.exeInstallUtil存在路径为:C:\WINDOWS\Microsoft.NET\Framework\.NET版本号复制C:\WINDOWS\Microsoft.NET\Framework\版本号 路径中的InstallUtil.exe 到bin/debug或bin/release文件夹中,在命令行窗口中直接运行命令InstallUtil.exe MyServiceLog.exe,在系统中注册这个服务,使它建立一个合适的注册项,如下图:
然后再window服务列表中,启动MyServiceLog服务卸载window 服务命令:InstallUtil.exe MyServiceLog.exe /u如果修改这个服务,但是路径没有变化的话是不需要重新注册服务的,直接停止服务,然后用新的文件覆盖原来的文件即可,如果路径发生变化,应该先卸载这个服务,然后重新安装这个服务。服务安装的bat内容:
服务卸载的bat内容:
安装完服务后,服务如下图所示:
Windows服务调试管理员方式运行Visual Studio 打开MySerivceLog项目在管理工具-〉服务里面启动MyServiceLog服务单击vs的调试 -〉附加到进程,如下图在附加到:选择里面勾选 自动确定要调试的代码类型
在'可用进程“列表中,选中你要调式的服务的可执行文件名单击 ”附加“按钮,即可进入调试状态在timer1_Elapsed方法里设置一个断点,然后等它执行,服务执行到该处时候会自动启动断点。 问题解决: