[技術] 如何用.NET建立Windows服務
# 什麼是Windows服務?
- 是一種需要長期運行的應用程式,它對於伺服器環境特別適合。
- 沒有使用者介面,並且也不會產生任何輸出可以看到。任何使用者消息都會被寫進Windows事件日誌。
- 電腦啟動時,服務會自動開始運行。
- 不需要用戶登入才能運行,它們能在包括這個系統內的任何使用者環境下運行。
- 通過服務控制管理器,Windows服務是可控制的,可以終止、暫停及啟動。
- 以Windows服務形式的產品有:Microsoft Exchange、SQL Server,還有別的如設置電腦時鐘的Windows Time服務。
# 建立一個Windows服務
這次要練習建立的這個服務,被啟動時會把一個項目資訊登記到一個資料庫當中來說明這個服務已經啟動了。在服務運行期間,它會在指定的時間間隔內定期建立一個資料庫專案記錄。服務停止時會建立最後一條資料庫記錄。這個服務會自動向Windows應用程式日誌當中紀錄它成功啟動或停止時的記錄。
我們可以透過Visual Studio來建立一個Windows服務,步驟如下:
1. 新建一個Windows服務。
2. 設計器會以設計模式打開,從工具箱的元件表當中拖動一個Timer物件到這個設計表面上
(注意: 要確保是從元件清單而不是從Windows表單清單當中使用Timer)
3. 設置Timer屬性,Enabled屬性為False,Interval屬性30000毫秒
4. 接著回到程式碼頁面,撰寫這個服務的功能。
# Windows服務的組成
在程式碼裡可以發現到,Windows服務using了System.ServiceProcess.Service。所有以.NET方式建立的Windows服務必須擴充這個類別。它會要求服務重載下面的方法:
- Dispose:清除任何管理和非管理資源(managed and unmanaged resources)
- OnStart:控制服務啟動
- OnStop:控制服務停止
# 資料庫表建立
1: CREATE TABLE [dbo].[MyServiceLog] (2: [in_LogId] [int] IDENTITY (1, 1) NOT NULL,
3: [vc_Status] [nvarchar] (40) 4: COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, 5: [dt_Created] [datetime] NOT NULL 6: ) ON [PRIMARY]
# 撰寫Windows服務範例
1: using System;
2: using System.Data.SqlClient;
3: using System.ServiceProcess;
4: 5: namespace WindowsService1
6: {7: public partial class Service1 : ServiceBase
8: { 9: 10: public Service1()
11: { 12: InitializeComponent(); 13: } 14: 15: protected override void OnStart(string[] args)
16: {17: this.timer1.Enabled = true;
18: this.LogMessage("Service Started");
19: } 20: 21: protected override void OnStop()
22: {23: this.timer1.Enabled = false;
24: this.LogMessage("Service Stopped");
25: } 26: 27: //Respond to the Elapsed event of the timer control
28: private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
29: {30: this.LogMessage("Service Running");
31: } 32: 33: // Log specified message to database
34: private void LogMessage(string Message)
35: {36: SqlConnection connection = null;
37: SqlCommand command = null;
38: try
39: {40: connection = new SqlConnection( "Server=localhost;Database=SampleDatabase;Integrated Security=false;User Id=sa;Password=;");
41: command = new SqlCommand("INSERT INTO MyServiceLog (vc_Status, dt_Created) VALUES ('" + Message + "',getdate())", connection);
42: connection.Open();43: int numrows = command.ExecuteNonQuery();
44: }45: catch( Exception ex )
46: { 47: System.Diagnostics.Debug.WriteLine(ex.Message); 48: }49: finally
50: { 51: command.Dispose(); 52: connection.Dispose(); 53: } 54: } 55: } 56: }
資料參考:http://pcedu.pconline.com.cn/empolder/net/0505/613681.html