用.NET創(chuàng)建Windows服務(wù)的方法第1/2頁(yè)
譯者說(shuō)明:我是通過(guò)翻譯來(lái)學(xué)習(xí)C#的,文中涉及到的有Visual Studio.NET有關(guān)操作,我都根據(jù)中文版的VS.NET顯示信息來(lái)處理的,可以讓大家不致有誤解。
作者:Mark Strawmyer
我們將研究如何創(chuàng)建一個(gè)作為Windows服務(wù)的應(yīng)用程序。內(nèi)容包含什么是Windows服務(wù),如何創(chuàng)建、安裝和調(diào)試它們。會(huì)用到System.ServiceProcess.ServiceBase命名空間的類。
什么是Windows服務(wù)?
Windows服務(wù)應(yīng)用程序是一種需要長(zhǎng)期運(yùn)行的應(yīng)用程序,它對(duì)于服務(wù)器環(huán)境特別適合。它沒(méi)有用戶界面,并且也不會(huì)產(chǎn)生任何可視輸出。任何用戶消息都會(huì)被寫進(jìn)Windows事件日志。計(jì)算機(jī)啟動(dòng)時(shí),服務(wù)會(huì)自動(dòng)開(kāi)始運(yùn)行。它們不要用戶一定登錄才運(yùn)行,它們能在包括這個(gè)系統(tǒng)內(nèi)的任何用戶環(huán)境下運(yùn)行。通過(guò)服務(wù)控制管理器,Windows服務(wù)是可控的,可以終止、暫停及當(dāng)需要時(shí)啟動(dòng)。
Windows 服務(wù),以前的NT服務(wù),都是被作為Windows NT操作系統(tǒng)的一部分引進(jìn)來(lái)的。它們?cè)赪indows 9x及Windows Me下沒(méi)有。你需要使用NT級(jí)別的操作系統(tǒng)來(lái)運(yùn)行Windows服務(wù),諸如:Windows NT、Windows 2000 Professional或Windows 2000 Server。舉例而言,以Windows服務(wù)形式的產(chǎn)品有:Microsoft Exchange、SQL Server,還有別的如設(shè)置計(jì)算機(jī)時(shí)鐘的Windows Time服務(wù)。
創(chuàng)建一個(gè)Windows服務(wù)
我們即將創(chuàng)建的這個(gè)服務(wù)除了演示什么也不做。服務(wù)被啟動(dòng)時(shí)會(huì)把一個(gè)條目信息登記到一個(gè)數(shù)據(jù)庫(kù)當(dāng)中來(lái)指明這個(gè)服務(wù)已經(jīng)啟動(dòng)了。在服務(wù)運(yùn)行期間,它會(huì)在指定的時(shí)間間隔內(nèi)定期創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)項(xiàng)目記錄。服務(wù)停止時(shí)會(huì)創(chuàng)建最后一條數(shù)據(jù)庫(kù)記錄。這個(gè)服務(wù)會(huì)自動(dòng)向Windows應(yīng)用程序日志當(dāng)中登記下它成功啟動(dòng)或停止時(shí)的記錄。
Visual Studio .NET能夠使創(chuàng)建一個(gè)Windows服務(wù)變成相當(dāng)簡(jiǎn)單的一件事情。啟動(dòng)我們的演示服務(wù)程序的說(shuō)明概述如下。
1. 新建一個(gè)項(xiàng)目
2. 從一個(gè)可用的項(xiàng)目模板列表當(dāng)中選擇Windows服務(wù)
3. 設(shè)計(jì)器會(huì)以設(shè)計(jì)模式打開(kāi)
4. 從工具箱的組件表當(dāng)中拖動(dòng)一個(gè)Timer對(duì)象到這個(gè)設(shè)計(jì)表面上 (注意: 要確保是從組件列表而不是從Windows窗體列表當(dāng)中使用Timer)
5. 設(shè)置Timer屬性,Enabled屬性為False,Interval屬性30000毫秒
6. 切換到代碼視圖頁(yè)(按F7或在視圖菜單當(dāng)中選擇代碼),然后為這個(gè)服務(wù)填加功能
Windows服務(wù)的構(gòu)成
在你類后面所包含的代碼里,你會(huì)注意到你所創(chuàng)建的Windows服務(wù)擴(kuò)充了System.ServiceProcess.Service類。所有以.NET方式建立的Windows服務(wù)必須擴(kuò)充這個(gè)類。它會(huì)要求你的服務(wù)重載下面的方法,Visual Studio默認(rèn)時(shí)包括了這些方法。
• Dispose – 清除任何受控和不受控資源(managed and unmanaged resources)
• OnStart – 控制服務(wù)啟動(dòng)
• OnStop – 控制服務(wù)停止
數(shù)據(jù)庫(kù)表腳本樣例
在這個(gè)例子中使用的數(shù)據(jù)庫(kù)表是使用下面的T-SQL腳本創(chuàng)建的。我選擇SQL Server數(shù)據(jù)庫(kù)。你可以很容易修改這個(gè)例子讓它在Access或任何你所選擇的別的數(shù)據(jù)庫(kù)下運(yùn)行。
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服務(wù)樣例
下面就是我命名為MyService的Windows服務(wù)的所有源代碼。大多數(shù)源代碼是由Visual Studio自動(dòng)生成的。
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();
}
}
}
}
相關(guān)文章
Entity?Framework使用ObjectContext類
這篇文章介紹了Entity?Framework使用ObjectContext類的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06unity實(shí)現(xiàn)文字滾動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了unity實(shí)現(xiàn)文字滾動(dòng)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-02-02C# 實(shí)現(xiàn)Trim方法去除字符串前后的所有空格
這篇文章主要介紹了C# 實(shí)現(xiàn)Trim方法去除字符串前后的所有空格,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12unity scrollRect實(shí)現(xiàn)按頁(yè)碼翻頁(yè)效果
這篇文章主要為大家詳細(xì)介紹了unity scrollRect實(shí)現(xiàn)按頁(yè)碼翻頁(yè)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04C#中comboBox實(shí)現(xiàn)三級(jí)聯(lián)動(dòng)
給大家分享了C#中comboBox實(shí)現(xiàn)三級(jí)聯(lián)動(dòng)的全部代碼,代碼經(jīng)過(guò)測(cè)試,有興趣的朋友跟著做一下。2018-03-03C#中StringBuilder用法以及和String的區(qū)別分析
當(dāng)我們?cè)诔鯇W(xué)使用C#時(shí),常常會(huì)不知道該用StringBuilder合適還是用String高效,下面是我在學(xué)習(xí)當(dāng)中對(duì)StringBuilder和String的區(qū)別總結(jié),分享給大家。2013-03-03C#對(duì)DataTable中的某列進(jìn)行分組
這篇文章介紹了C#對(duì)DataTable某列進(jìn)行分組的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-03-03