用C#編寫Windows服務

來源:互聯網
上載者:User
文章目錄
  • 附加正在啟動並執行Windows服務

前言:編寫一個Windows服務程式,定時從資料庫中拿出記錄發送郵件。

測試環境:Visual Studio 2005 SP1、Windows Server 2003 SP2

一、建立項目

開啟VS2005,建立一個“Windows 服務”項目。

二、添加Timer

展開“工具箱”,在“組件”標籤下找到“Timer”雙擊,這時就添加了一個Timer組件,修改“Name”屬性為“timEmail”、“Enabled”為“false”、“Interval”為“60000”。

接下來要做一些修補工作,不知是VS2005的BUG還是我沒找著地方,在VS2003下是不存在該問題的:剛從“組件”下添加的“Timer”按理說應該來自“System.Timers命名空間”,也只有“System.Timers.Timer”才能在Windows服務程式中正常工作,但是現在這個Timer卻是屬於“System.Windows.Forms.Timer”的。所以得稍作修改,開啟“.Designer.cs”檔案,修改如下:

#region 組件設計器產生的程式碼//........以上略
/// <summary> 
/// 設計器支援所需的方法 - 不要
/// 使用代碼編輯器修改此方法的內容。
/// </summary>
private void InitializeComponent()
{
            this.components = new System.ComponentModel.Container();
            //this.timEmail = new System.Windows.Forms.Timer(this.components);原
            this.timEmail = new System.Timers.Timer();//改
            this.timEmail.Interval = 60000;
            this.ServiceName = "Service1";}
#endregion
//private System.Windows.Forms.Timer timEmail;原
private System.Timers.Timer timEmail;//改

 三、添加設定檔

服務每次調用設定檔,擷取一些基本參數,這樣一些變更就可直接修改設定檔而不必修改代碼。建立ServiceConfig.xml存放於項目“Bin\Debug\”下:

<?xml version="1.0" encoding="utf-8" ?> 
<serviceConfig>
    <serviceItem 
        name="sendEmail" 
        enable="true" 
        elapsed="60000" 
        connectionString="your database connection..." 
        smtp="smtp address" 
        account="your email account..." 
        password="your password..." >
    </serviceItem>
</serviceConfig>

四、以下是實現代碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Xml;//操作設定檔
using System.IO;//寫日誌
using System.Threading;//使用線程

namespace ClientWindowsService
{
    public partial class ClientService : ServiceBase
    {
        public ClientService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            //服務啟動
      this.timEmail.Enabled = true;
            this.tSendEmail();
        }

        protected override void OnStop()
        {
            //服務停止
      this.timEmail.Enabled = false;
        }

        private void timEmail_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //定時器
      this.tSendEmail();
        }

        //開啟新進程發送郵件
    private void tSendEmail()
        {
            Thread t = new Thread(new ThreadStart(sendEmail));
            t.Start();
        }

        //發送郵件函數
    private void sendEmail()
        {
            XmlDocument doc = new XmlDocument();
            //添加System.Windows.Forms引用,擷取執行目錄
      string configFile = System.Windows.Forms.Application.StartupPath.ToString() + "\ServiceConfig.xml";
            doc.Load(@configFile);
            XmlElement root = doc.DocumentElement;
            foreach (XmlNode node in root)
            {
                //如果設定檔中開啟服務
        if (node.Attributes["name"].Value == "sendEmail" && node.Attributes["enable"].Value == "true")
                {
                    try
                    {
                        //讀取資料庫,發送郵件操作,略
                    }
                    catch (Exception error)
                    {
                        //寫錯誤記錄檔
            using (StreamWriter sw = new StreamWriter(System.Windows.Forms.Application.StartupPath.ToString() + @"" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", true, System.Text.Encoding.UTF8))
                        {
                            sw.WriteLine(DateTime.Now.ToString() + ":");
                            sw.WriteLine(error.ToString());
                            sw.WriteLine("---------------------------------------------");
                            sw.Close();
                        }
                    }
                }
            }//end foreach
        }

    }//end class
}//end namespace

五、布署服務

在設計模式下右鍵-->添加安裝程式-->設定serviceProcessInstaller1的Account為LocalSystem

設定serviceInstaller1的StartType為Automatic

編譯

在命令模式下執行:%systemroot%\microsoft.net\framework\v2.0.50727\installUtil.exe D:\項目目錄\bin\Debug\可執行檔名.exe
在每次需要修改Windows服務時,這就會要求你卸載和重新安裝這個服務。不過要注意在卸載這個服務前,最好確保服務管理主控台已經關閉,這會是一個很好的習慣。如果沒有這樣操作的話,你可能在卸載和重安裝Windows服務時會遇到麻煩。僅卸載服務的話,可以執行相的InstallUtil命令用於登出服務,不過要在後面加一個/u命令開關。

調試Windows服務

  從另外的角度度看,調試Windows服務絕不同於一個普通的應用程式。調試Windows服務需求的步驟更多。服務不能象你對普通應用程式做的那樣,只要簡單地在開發環境下執行就可以調試了。服務必須首先被安裝和啟動,這一點在前面部分我們已經做到了。為了便於跟蹤調試代碼,一旦服務被啟動,你就要用Visual Studio把啟動並執行進程附加進來(attach)。記住,對你的Windows服務做的任何修改都要對這個服務進行卸載和重安裝。

附加正在啟動並執行Windows服務

  為了偵錯工具,有些附加Windows服務的操作說明。這些操作假定你已經安裝了這個Windows服務並且它正在運行。

1. 用Visual Studio裝載這個項目
2. 點擊“調試”菜單
3. 點擊“進程”菜單
4. 確保 顯示系統進程 被選
5. 在 可用進程 列表中,把進程定位於你的可執行檔名稱上點擊選中它
6. 點擊 附加 按鈕
7. 點擊 確定
8. 點擊 關閉
9. 在timer1_Elapsed方法裡設定一個斷點,然後等它執行

六、代碼下載
http://files.cnblogs.com/linckle/log.rar

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.