一个简单的windows Service示例[转载]

 介绍

Windows Services能让你创建长期运行在windows sessioin中的程序,这种程序能够在操作系统启动时自动运行,并且能够手动暂停、停止甚至重启。

如果你的应用需要长期运行,但需要不影响同一台机器上的其他用户,service可以完美地解决这个问题。你可以使用特定账户运行service,而不是使用登录账户或者默认账户。

对用户来说,windows services没有界面,所以它不能像不同应用程序那样调试,但是可以作为一个进程调试。在运行状态中,.NET有非常友好的工具能进行进程调试,按下Ctrl + Alt + P快捷键使用。

背景 

通过查找大量站点,我找到了很多通过ServiceController class管理系统服务的代码.通过查找MSDN,我找到了创建这个简单服务的非常棒的代码。希望这个服务对初级架构师有帮助。

使用代码

首先你应该打开VS.NET,然后创建一个Windows Service 项目,命名为MyNewService(如图)

Winows Service New Project

项目模板自动添加名为Service1的组件类,该类继承自System.ServiceProcess.ServiceBase.

双击打开Service1组件类,在设计模式状态,查看属性窗口,设置ServiceName属性为MyNewService,设置Name属性为MyNewService,设置AutoLog属性为true。

在代码编辑器中,在Main方法中创建一个MyNewService的实例。如果重命名了服务名,Main方法中类名不会被修改,访问Main方法,重新生成代码。

Main方法代码如下:
static void Main()
{    
  System.ServiceProcess.ServiceBase[] ServicesToRun;    
     ServicesToRun = new   System.ServiceProcess.ServiceBase[] { new MyNewService() };
     System.ServiceProcess.ServiceBase.Run(ServicesToRun);  }

在下一个章节,你会在windows services中添加一个event Log。event Log和windows services没有任何关系。这里EventLog组件作为一个示例添加到windows services。

添加Event Log到你的service中:

  1. 在项目浏览窗口,双击服务文件,定位到服务文件的设计界面。
  2. 从工具箱中拖一个EventLog组件到界面上。
  3. 定位到代码编辑界面。
  4. 定义eventlog。

代码如下

public MyNewService()
{
     InitializeComponent()
    if(!System.Diagnostics.EventLog.SourceExists("DoDyLogSourse"))
    System.Diagnostics.EventLog.CreateEventSource("DoDyLogSourse","DoDyLog");
    eventLog1.Source = "DoDyLogSourse";
    // the event log source by which
     //the application is registered on the computer
     eventLog1.Log = "DoDyLog";
}

在代码编辑界面,你可以看到,在创建项目时OnStart方法会被自动重载,在该方法内编写代码决定在服务启动时要做什么事情。

protected override void OnStart(string[] args)
{
     eventLog1.WriteEntry("my service started"); 
}
一旦Service开始运行,OnStart方法必须要返回操作系统。他不能永远循环或者阻塞。你能使用System.Timers.Timer组件设置简单的选择机制。在OnStart方法中,
你能设置组件的参数,把Timer.Enabled的属性设置为true。在服务运行期间,服务会做监控,会周期性调用Event
为了定义服务停止时做什么事情,你可以在OnStop方法中编写代码。OnStop方法在你创建项目时会自动重载。
protected override void OnStop()
{
     eventLog1.WriteEntry("my service stoped");
}

你还能重载OnPause,OnContinue和OnShutdown方法。在这些方法内你可以定义要做的事情。如下代码展示了重载OnContinue方法。

protected override void OnContinue()
{
    eventLog1.WriteEntry("my service is continuing in working");
}

在安装widows service服务是是如果需要自定义操作,可以通过Installer class实现。VS能为服务创建特定的Instalers,并且添加到项目中。

为服务创建Installers:

返回到服务的设计界面

  1. 在属性窗口底部单击链接“Add Installer”。默认情况,一个包含两个Installers的组件会被添加到你的项目。 The component is named ProjectInstaller, and the installers it contains are the installer for your service and the installer for the service's associated process.
  2. 访问ProjectInstaller的设计界面,单击ServiceInstaller1.
  3. 在属性窗口设置ServiceName 属性为MyNewService.
  4. 设置StartType属性为Automatic.

提示

为了避免询问系统用户名和密码,你必须把serviceProcessInstaller的Account属性选择为LocalSystem。打开ProjectInstaller,切换到设计界面,选择ServiceProcessInstaller,打开属性窗口,选择Account属性为LocalSystem。或者你可以手动处理,创建一个继承System.Configuration.Install.Installer的类实现相同的操作,代码如下:

[RunInstaller(true)]

public class ProjectInstaller : System.Configuration.Install.Installer

{
private System.ServiceProcess.ServiceProcessInstaller
                                  serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller serviceInstaller1;
/// <summary>
/// Required designer variable.
/// </summary> private System.ComponentModel.Container components = null;

public ProjectInstaller()
   // This call is required by the Designer.
   InitializeComponent();

   // TODO: Add any initialization after the InitComponent call
}
private void InitializeComponent()
{
   this.serviceProcessInstaller1 =
     new System.ServiceProcess.ServiceProcessInstaller();
   this.serviceInstaller1 =
     new System.ServiceProcess.ServiceInstaller();
   // serviceProcessInstaller1
   //
   this.serviceProcessInstaller1.Account =
     System.ServiceProcess.ServiceAccount.LocalSystem;
   this.serviceProcessInstaller1.Password = null;
   this.serviceProcessInstaller1.Username = null;
   //
   // serviceInstaller1
   //
   this.serviceInstaller1.ServiceName = "MyNewService";
   this.serviceInstaller1.StartType =
     System.ServiceProcess.ServiceStartMode.Automatic;

   //
   // ProjectInstaller
   //
   this.Installers.AddRange
     (new System.Configuration.Install.Installer[]
   {
       this.serviceInstaller1,
       this.serviceInstaller1});
   }
}

}

编译你的服务项目

  1. 打开项目的属性窗口。
  2. 选择Common Properties,然后选择General。
  3. 在右边属性窗口,选择Startup Object属性,选择MyNewService。
  4. 编译你的服务项目。 

Service Project Property Page

服务项目编译完之后,就可以被部署。一个安装文件项目将安装编译过的文件和运行Installers安装windows service。为了创建一个完整的安装文件项目,你需要把Service项目的输出文件添加到安装文件项目,并且添加custom Action来安装MyNewService。

为你的服务创建一个安装文件项目

  1. 打开文件菜单,选择新项目.
  2. 在项目类型面板,选择安装和部署项目文件夹。
  3. 在模板面板,选择安装项目。命名为MyServiceSetup。

你已经在解决方案中创建了一个安装项目,接下来把Windows service的输出文件“MyNewService”添加到安装项目中。

Service Setup Project

把MyNewService.exe添加到安装项目中

  1. 在解决方案窗口,右键点击MyServiceSetup项目,选择Add,选择Project Output,弹出一个窗口.
  2. 选择MyNewService.
  3. 在列表窗口中,选择主要输出,单击OK。

    MyNewService的输出选项已经添加到安装文件项目。现在添加Custom action 来安装MyNewService.exe。

在安装文件项目中添加custom action

  1. 在解决方案窗口,右击安装项目,选择View,然后选择custom actions,将会出现custom action的编辑器。
  2. 在custom actions编辑器,右击custom actions 节点,选择“Add custom action”,将会弹出列表选择窗口。
  3. 在列表窗口中双击打开application folder,在MyNewService中选择主要的输出文件,选择确定按钮。主要的输出文件被添加到custom action的四个节点中,这四个节点为Install,Commit,Rollback,Uninstall。
  4. 编译安装项目。

安装Windows Service

找到安装项目被保存的目录,运行.msi文件安装MyNewService.exe。

Service Setup

启动和终止你的服务

  1. 通过以下方式代开Service controll manager:
    • 对于windows 2000 Professional 的系统,在桌面上右击我的电脑,选择管理,在计算机管理控制台,展开服务和应用程序节点。

      - 或者 -

    • 对于Window 2000 Server,点击“开始”按钮,选择程序,单击管理工具,然后单击服务。
      - 或者 -
    • 点击“开始 ”按钮,选择“运行”,输入Services.msc,打开服务控制台。

提示:在Windows NT 4.0的版本中,在控制面板中打开。

  2. 查看服务列表中是否存在MyNewService。

  3. 如果存在,选中服务,单击右键,然后单击开始。

右键选中服务,单击停止。

Admin tools Services

检查服务的event log 输出

  1. 打开Server Explorer,访问Event Logs节点。更多信息,查看Working with event logs in server explorer。

    提示:Server Explorer的Servers Node在Visual Basic 和Visual C# .NET 的标准版本中是无效的。

    Sample screenshot

卸载服务

  • 选择控制面板,选择添加/删除程序,定位到你的服务,单击卸载。
  • 或者通过双击.msi文件,选择Uninstall卸载。

另外,可以通过命令行工具安装和卸载Windows Services

使用 installutil MyNewService.exe安装服务,使用installutil \u MyNewService.exe卸载服务,也可以把命令放在批处理文件中,通过批处理文件安装和卸载服务。

posted @ 2010-09-30 08:43  mutounannan  阅读(301)  评论(0编辑  收藏  举报