如何:以编程方式编写服务

更新:2007 年 11 月

如果选择不使用 Windows 服务项目模板,可以通过自行设置继承和其他基础结构元素来编写自己的服务。当以编程方式创建服务时,必须执行模板原本可以会为您处理的几个步骤:

  • 必须将服务类设置为从 ServiceBase 类继承。

  • 必须为服务项目创建一个 Main 方法,定义要运行的服务并对这些服务调用 Run 方法。

  • 必须重写 OnStartOnStop 过程,并填写希望它们运行的任何代码。

    76477d2t.alert_note(zh-cn,VS.90).gif说明:

    Visual Studio 标准版中不提供“Windows 服务”模板及相关功能。

以编程方式编写服务

  1. 创建一个空项目,然后按下列这些步骤创建到所需命名空间的引用:

    1. 在“解决方案资源管理器”中右击“引用”节点,再单击“添加引用”。

    2. 在“.NET Framework”选项卡中,滚动到“System.dll”并单击“选择”。

    3. 滚动到“System.ServiceProcess.dll”并单击“选择”。

    4. 单击“确定”。

  2. 添加一个类并将其配置为从 ServiceBase 继承:

    Public Class UserService1
       Inherits System.ServiceProcess.ServiceBase
    End Class
    
    public class UserService1 : System.ServiceProcess.ServiceBase  
    {
    }
    
    public class UserService1 extends System.ServiceProcess.ServiceBase
    {
    }
    
  3. 添加下列代码来配置服务类:

    Public Sub New()
        Me.ServiceName = "MyService2"
        Me.CanStop = True
        Me.CanPauseAndContinue = True
        Me.AutoLog = True
    End Sub
    
     public UserService1() 
        {
            this.ServiceName = "MyService2";
            this.CanStop = true;
            this.CanPauseAndContinue = true;
            this.AutoLog = true;
        }
    
     public UserService1() 
        {
            this.set_ServiceName("MyService2");
            this.set_CanStop(true);
            this.set_CanPauseAndContinue(true);
            this.set_AutoLog(true);
        }
    
  4. 为类创建 Main 方法,并使用它来定义类将包含的服务;userService1 是类的名称:

    Shared Sub Main()
      System.ServiceProcess.ServiceBase.Run(New UserService1)
    End Sub
    
     public static void Main()
        {
            System.ServiceProcess.ServiceBase.Run(new UserService1());
        }
    
     public static void main()
        {
            System.ServiceProcess.ServiceBase.Run(new UserService1());
        }
    
  5. 重写 OnStart 方法,并定义希望在服务启动时发生的任何处理。

    Protected Overrides Sub OnStart(ByVal args() As String)
      ' Insert code here to define processing.
    End Sub
    
     protected override void OnStart(string[] args)
        {
            // Insert code here to define processing.
        }
    
     protected void OnStart(System.String[] args)
        {
            // Insert code here to define processing.
        }
    
  6. 重写要为其定义自定义处理的其他任何方法,并编写代码以确定服务在各种情况中应采取的操作。

  7. 添加服务应用程序所必需的安装程序。有关更多信息,请参见如何:将安装程序添加到服务应用程序

  8. 通过从“生成”菜单中选择“生成解决方案”来生成项目。

    76477d2t.alert_note(zh-cn,VS.90).gif说明:

    不要通过按 F5 来运行项目,不能以这种方式运行服务项目。

  9. 创建一个安装项目和自定义操作来安装服务。有关示例,请参见演练:在组件设计器中创建 Windows 服务应用程序

  10. 安装服务。有关更多信息,请参见如何:安装和卸载服务

请参见

任务

如何:创建 Windows 服务

如何:将安装程序添加到服务应用程序

如何:记录关于服务的信息

演练:在组件设计器中创建 Windows 服务应用程序

演练:创建自定义操作

概念

Windows 服务应用程序介绍

安装项目