C# windows service note

  • 408
  • 0

摘要:C# windows service note

需求:每隔一段時間要執行一些工作,最適合的方案似乎是 windows service。

隨便 google都能找到很詳細的教學,所以跳過,講些自己遇到的狀況…

習慣先開個測試專案亂寫一通,能 run了再加到正式專案,不過 service的 name不能重複,而且 VS的介面不會自動改 service的 name:


        ///  
        /// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器
        /// 修改這個方法的內容。
        /// 
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            this.ServiceName = "Service1"; // 這行必需手動改
        }

如果想加入多個服務的話…


    static class Program
    {
        /// 
        /// 應用程式的主要進入點。
        /// 
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new Service2() // 這裡看起來只要繼承 ServiceBase就能加入新服務,但我試都只會跑第一個
            };
            ServiceBase.Run(ServicesToRun);
        }
    }

後來自己做一個小工具當二房東XD


    interface IWindowsService
    {
        /// 
        /// 執行頻率,單位:秒
        /// 
        long ExecFrequence { get; }
        void StartWork(object sender, ElapsedEventArgs e);
        void StopWork();
    }

    public partial class MainService : ServiceBase
    {
        List serviceList;
        List timerList;

        public MainService()
        {
            InitializeComponent();

            serviceList = new List
            {
                new MyService(),//實作 IWindowsService的自訂類別

            };
            timerList = new List();
        }

        protected override void OnStart(string[] args)
        {
            Common.Log("MainService On Start");// 只是寫文字檔而已

            foreach (var service in serviceList)
            {
                service.StartWork(null, null);// timer要等時間到才會執行,先手動執行第一次

                Timer timer = new Timer();
                timer.Elapsed += new ElapsedEventHandler(service.StartWork);
                timer.Interval = service.ExecFrequence * 1000;
                timer.Start();

                timerList.Add(timer);
            }
        }

        protected override void OnStop()
        {
            Common.Log("MainService On Stop");

            foreach (var service in serviceList)
            {
                service.StopWork();
            }

            foreach (var timer in timerList)
            {
                timer.Stop();
            }
            timerList.Clear();
        }

然後服務安裝的 batch檔長這樣:


%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe "xxx\WindowsService.exe"
pause

安裝完要移除只要在 "xxx\WindowsService.exe"前面加個 -u,然後重開機。但我試是沒必要移除,暫停服務、編譯、開啟服務,就能套新邏輯了。