Windows服務代碼練習

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;

namespace WindowsServiceTest
{
    public partial class ServiceTest : ServiceBase
    {
        public ServiceTest()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args) //啓動服務的時候寫個日誌
        {
            proccess.Start();
        
        }

        protected override void OnStop() //關閉服務的時候再寫個日誌
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Stop.");
            }
        }

        public static class proccess
        {
            public static void Start()
            {
               ThreadStart start = new ThreadStart(ThreadAction);
               Thread th = new Thread(start);
               th.IsBackground = true;
               th.Start();
            }
        }
        public static void ThreadAction()
        {
            while(true)
            { 
                try
                {
                    //do something
                    System.Threading.Thread.Sleep(30000);
                }
                catch{}
            }
        }
    }
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章