2019/06/03

C#.Net Windows Service

Windows Service蠻久了,不過還蠻常用到,寫個文章來記錄一下
執行時如果遇到「服務並未以適時的方式回應啟動或控制請求。」可能是程式碼有錯,需要仔細檢查程式碼
參考這篇「如何對Windows Service進行除錯」也不見得能從Console的方式找到錯誤,在寫Windows Service時需要謹慎,以免程式碼過多而不容易找到錯誤

要將服務安裝上去需要透過Installutil.exe這個工具,路徑為
%WINDIR%\Microsoft.NET\Framework\Framework Version

我只會用到安裝與卸載,指令如下
# 安裝
installutil service.exe
# 卸載
installutil /u service.exe

下面有寫個Sample Code
Windows Service執行時會啟用Timer,每秒會輸出當前時間與日期至事件檢視器



Code:
using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Timers;

namespace CYFang
{
    /// <summary>
    /// Test_WindowsService
    /// </summary>
    public partial class Test_WindowsService : ServiceBase
    {
        /// <summary>
        /// Timer
        /// </summary>
        private System.Timers.Timer timer;
        /// <summary>
        /// Source name
        /// </summary>
        private String SourceName = "SourceName";
        /// <summary>
        /// Log name
        /// </summary>
        private String LogName = "LogName";

        /// <summary>
        /// Constructor
        /// </summary>
        public Test_WindowsService()
        {
            InitializeComponent();

            //確認紀錄是否存在
            if (!EventLog.SourceExists(SourceName))
            {
                //建立Windows紀錄
                EventLog.CreateEventSource(SourceName, LogName);
            }
            //setting source name
            eventLog1.Source = SourceName;
            //setting log name 
            eventLog1.Log = LogName;
        }

        /// <summary>
        /// 服務啟動時
        /// </summary>
        /// <param name="args">args</param>
        protected override void OnStart(string[] args)
        {
            eventLog1.WriteEntry("服務已啟動");
            timer = new System.Timers.Timer();
            int interval = 1000;
            timer.Interval = interval;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }

        /// <summary>
        /// 服務停止時
        /// </summary>
        protected override void OnStop()
        {
            if (timer != null)
            {
                timer.Stop();
                timer.Close();
                timer = null;
                eventLog1.WriteEntry("服務停止");
            }
        }

        /// <summary>
        /// 計時器啟動
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">event</param>
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            eventLog1.WriteEntry(DateTime.Now.ToString());
        }

    }

}