用.NET创建Windows服务的方法第1/2页

 更新时间:2007年03月16日 00:00:00   作者:  

译者说明:我是通过翻译来学习C#的,文中涉及到的有Visual Studio.NET有关操作,我都根据中文版的VS.NET显示信息来处理的,可以让大家不致有误解。

作者:Mark Strawmyer

我们将研究如何创建一个作为Windows服务的应用程序。内容包含什么是Windows服务,如何创建、安装和调试它们。会用到System.ServiceProcess.ServiceBase命名空间的类。


什么是Windows服务?


Windows服务应用程序是一种需要长期运行的应用程序,它对于服务器环境特别适合。它没有用户界面,并且也不会产生任何可视输出。任何用户消息都会被写进Windows事件日志。计算机启动时,服务会自动开始运行。它们不要用户一定登录才运行,它们能在包括这个系统内的任何用户环境下运行。通过服务控制管理器,Windows服务是可控的,可以终止、暂停及当需要时启动。

Windows 服务,以前的NT服务,都是被作为Windows NT操作系统的一部分引进来的。它们在Windows 9x及Windows Me下没有。你需要使用NT级别的操作系统来运行Windows服务,诸如:Windows NT、Windows 2000 Professional或Windows 2000 Server。举例而言,以Windows服务形式的产品有:Microsoft Exchange、SQL Server,还有别的如设置计算机时钟的Windows Time服务。


创建一个Windows服务

我们即将创建的这个服务除了演示什么也不做。服务被启动时会把一个条目信息登记到一个数据库当中来指明这个服务已经启动了。在服务运行期间,它会在指定的时间间隔内定期创建一个数据库项目记录。服务停止时会创建最后一条数据库记录。这个服务会自动向Windows应用程序日志当中登记下它成功启动或停止时的记录。

Visual Studio .NET能够使创建一个Windows服务变成相当简单的一件事情。启动我们的演示服务程序的说明概述如下。

1. 新建一个项目
2. 从一个可用的项目模板列表当中选择Windows服务
3. 设计器会以设计模式打开
4. 从工具箱的组件表当中拖动一个Timer对象到这个设计表面上 (注意: 要确保是从组件列表而不是从Windows窗体列表当中使用Timer)
5. 设置Timer属性,Enabled属性为False,Interval属性30000毫秒
6. 切换到代码视图页(按F7或在视图菜单当中选择代码),然后为这个服务填加功能


Windows服务的构成

在你类后面所包含的代码里,你会注意到你所创建的Windows服务扩充了System.ServiceProcess.Service类。所有以.NET方式建立的Windows服务必须扩充这个类。它会要求你的服务重载下面的方法,Visual Studio默认时包括了这些方法。

• Dispose – 清除任何受控和不受控资源(managed and unmanaged resources)
• OnStart – 控制服务启动
• OnStop – 控制服务停止

数据库表脚本样例

在这个例子中使用的数据库表是使用下面的T-SQL脚本创建的。我选择SQL Server数据库。你可以很容易修改这个例子让它在Access或任何你所选择的别的数据库下运行。

CREATE TABLE [dbo].[MyServiceLog] (
   [in_LogId] [int] IDENTITY (1, 1) NOT NULL,
   [vc_Status] [nvarchar] (40)
           COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
   [dt_Created] [datetime] NOT NULL
) ON [PRIMARY]


Windows服务样例

下面就是我命名为MyService的Windows服务的所有源代码。大多数源代码是由Visual Studio自动生成的。

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.ServiceProcess;

namespace CodeGuru.MyWindowsService
{
  public class MyService : System.ServiceProcess.ServiceBase
  {
   private System.Timers.Timer timer1;
   /// <remarks>
   /// Required designer variable.
   /// </remarks>
   private System.ComponentModel.Container components = null;

   public MyService()
   {
       // This call is required by the Windows.Forms
       // Component Designer.
     InitializeComponent();
   }

   // The main entry point for the process
   static void Main()
   {
     System.ServiceProcess.ServiceBase[] ServicesToRun;

     ServicesToRun = new System.ServiceProcess.ServiceBase[]
{ new MyService() };

     System.ServiceProcess.ServiceBase.Run(ServicesToRun);
   }

   /// <summary>
   /// Required method for Designer support - do not modify
   /// the contents of this method with the code editor.
   /// </summary>
   private void InitializeComponent()
   {
     this.timer1 = new System.Timers.Timer();
     ((System.ComponentModel.ISupportInitialize)
(this.timer1)).BeginInit();
     //
     // timer1
     //
     this.timer1.Interval = 30000;
     this.timer1.Elapsed +=
   new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
     //
     // MyService
     //
     this.ServiceName = "My Sample Service";
     ((System.ComponentModel.ISupportInitialize)
(this.timer1)).EndInit();

   }

   /// <summary>
   /// Clean up any resources being used.
   /// </summary>
   protected override void Dispose( bool disposing )
   {
     if( disposing )
     {
      if (components != null)
      {
         components.Dispose();
      }
     }
     base.Dispose( disposing );
   }

   /// <summary>
   /// Set things in motion so your service can do its work.
   /// </summary>
   protected override void OnStart(string[] args)
   {
     this.timer1.Enabled = true;
     this.LogMessage("Service Started");
   }

   /// <summary>
   /// Stop this service.
   /// </summary>
   protected override void OnStop()
   {
     this.timer1.Enabled = false;
     this.LogMessage("Service Stopped");
   }

   /*
    * Respond to the Elapsed event of the timer control
    */
   private void timer1_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)
   {
     this.LogMessage("Service Running");
   }

   /*
    * Log specified message to database
    */
   private void LogMessage(string Message)
   {
     SqlConnection connection = null;
     SqlCommand command = null;
     try
     {
      connection = new SqlConnection(
"Server=localhost;Database=SampleDatabase;Integrated
Security=false;User Id=sa;Password=;");
command = new SqlCommand(
"INSERT INTO MyServiceLog (vc_Status, dt_Created)
VALUES ('" + Message + "',getdate())", connection);
      connection.Open();
      int numrows = command.ExecuteNonQuery();
     }
     catch( Exception ex )
     {
      System.Diagnostics.Debug.WriteLine(ex.Message);
     }
     finally
     {
      command.Dispose();
      connection.Dispose();
     }
   }
  }
}

相关文章

  • 基于C#实现高效示波器功能

    基于C#实现高效示波器功能

    这篇文章介绍了用 C#实现示波器功能的方法,包括使用 WinForm 及多种曲线控件,阐述了原理和思路,如定义缓存数据的队列、转化数组刷新显示等,还提到注意事项及扩展特性,最后呼吁点赞支持和交流,需要的朋友可以参考下
    2024-12-12
  • C# List引用类型克隆的3种方法

    C# List引用类型克隆的3种方法

    这篇文章主要给大家介绍了关于C# List引用类型克隆的3种方法,包括反射、序列化(依赖Newtonsoft.Json) 以及序列化(BinaryFormatter)的实现方法,需要的朋友可以参考借鉴,下面来一起看看吧
    2019-01-01
  • Stream.Write 与 StreamWriter.Write 的不同

    Stream.Write 与 StreamWriter.Write 的不同

    Stream.Write 与 StreamWriter.Write 是我们在向流中写数据时,最常用的方法。下面就详细讲解这两个方法。
    2013-04-04
  • C#和lua相互调用的方法教程

    C#和lua相互调用的方法教程

    lua是一种脚本语言,可以方便的移植到各种宿主语言中,并且可以支持热更新,在游戏开发中也能当做主要的语言来编写游戏的逻辑,所以这篇文章主要给大家介绍了关于C#和lua相互调用的方法教程,需要的朋友可以参考下。
    2017-11-11
  • C#开启线程的四种方式小结

    C#开启线程的四种方式小结

    在C#中,多线程编程是处理并发操作、提高程序性能的重要手段,C#提供了多种方式来创建和管理线程,下面将介绍四种常用的开启线程的方法,并附上相应的实现代码,需要的朋友可以参考下
    2024-06-06
  • C#中使用UDP通信实例

    C#中使用UDP通信实例

    这篇文章主要介绍了C#中使用UDP通信实例,非常实用的技巧,需要的朋友可以参考下
    2014-08-08
  • List转换成DataSet实现代码

    List转换成DataSet实现代码

    怎样把List转换成DataSet本人很是疑惑,于是搜集整理一番,需要的朋友可以参考下
    2012-12-12
  • 轻松学习C#的方法

    轻松学习C#的方法

    轻松学习C#的方法,对C#的方法感兴趣的朋友可以参考本篇文章,帮助大家更灵活的运用C#的方法
    2015-11-11
  • c#通过反射实现对象自动映射的实现

    c#通过反射实现对象自动映射的实现

    本文主要介绍了c#通过反射完成对象自动映射的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-02-02
  • C# 线性插值的实现示例

    C# 线性插值的实现示例

    线性插值是针对一维数据的插值方法,本文主要介绍了C# 线性插值的实现示例,具有一定的参考价值,感兴趣的可以了解一下
    2024-03-03

最新评论