前言
net 为创建 windows service 提供了专门的类库, 结束了以前开发 windows service 窘迫的局面。 你甚至可以不用添加一行代码,就可以用 wizard 生成一个 windows service 。
** 一、 用 wizard 生成最基本的框架 **
**  **
此时,系统会为你生成一个框架,部分主要源代码如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
namespace WindowsService1
{
public class Service1 : System.ServiceProcess.ServiceBase
{
private System.ComponentModel.Container components = null ;
public Service1()
{
InitializeComponent();
}
static void Main ()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this .ServiceName = "Service1";
}
protected override void Dispose( bool disposing )
{
if ( disposing )
{
if (components != null )
{
components.Dispose();
}
}
base .Dispose( disposing );
}
protected override void OnStart( string [] args)
{
}
protected override void OnStop()
{
}
}
}
有必要将其结构讲解一下。其中, System.ServiceProcess 就是关键所在,是引入 windows service 的地方。其中的 OnStart() 、 OnStop() 两个函数能够被 windows 服务管理器或者 MMC 调用,进行服务的启动、停止。
** 二、 构建一个服务 **
该框架提供了一个空的服务,什么也不能做。所以我们要给它添加代码。比如,我想
做一个能够扫描数据库的服务,要求每次扫描完之后间隔一秒钟,然后继续扫描。
根据上面的要求,初步设想需要一个 timer 类,查命名空间,发现有二个不同的 timer 类,他们是:
1、 System.Windows.Forms.Timer
2、 System.Timers.Timer
还有一个 System.Threading ,带有 sleep 方法
究竟该用哪个呢?
细查 MSDN ,会找到只有 2 适合,对于 1 来说, timer 控制时间不够精确,对于线程来说,实现比较困难。
** 三、 规划一下流程 **
基于该服务的要求,确定服务的流程如下:

为此,我们定义两个函数: _Scan(bool _judge) 、 _DO_Something()
然后引入 System.Timers 命名空间,并且定义一个 _timer 对象 , 这些代码如下:
1 、 using System.Timers; // 引入 System.Timers
2 、 public System.Timers.Timer _timer; // 定义对象 _timer
3 、 public bool _Scan( bool _judge)
{
//TODO
}
4 、 public void _DO_Something()
{
//TODO
}
然后在 InitializeComponent() 里边把 _timer 的 Elapsed 事件添加上,代码如下:
this ._timer.Elapsed += new System.Timers.ElapsedEventHandler( this ._timer_Elapsed) ;
定义 _timer_Elapsed 事件,代码如下:
private void _timer_Elapsed( object sender, System.Timers.ElapsedEventArgs e)
{
_timer.Interval=1000;
_timer.Enabled= false ;
if (_Scan()== true )
{
_DO_Something();
}
_timer.Enabled= true ;
}
最后,我们不要忘记添加 windows service 的 installer ,也是一个 wizard ,基本上不需要添加一行代码。然后编译,生成一个可执行文件。注意:因为这不是普通的可执行文件,所以不能通过双击实现运行,只能通过 installutil YourServiceName 、 NET START YourServiceName 、 NET STOP YourServiceName 、 installutil/u YourServiceName 来进行该服务的安装、启动、停止、暂停(可选)、卸载。最好是做成批处理文件,一劳永逸。^_^
_ tojike _