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