用.NET建立Windows服務的方法第1/2頁

來源:互聯網
上載者:User
文章目錄
  • 什麼是Windows服務?
  • 建立一個Windows服務
  • Windows服務的構成
  • 資料庫表指令碼範例
  • Windows服務範例

譯者說明:我是通過翻譯來學習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();
}
}
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.