C#創建Windows Service(Windows 服務)

一、創建Windows Service項目

1. 對服務命名(Service1——屬性,設置ServiceName的值TestService

2. 添加安裝程序(服務設計界面——右擊——添加安裝程序)

3. 設置服務安裝之後自動啓動(ProjectInstaller設計界面——添加AfterInstall事件),代碼如下:

     
        public ProjectInstaller()
        {
            InitializeComponent();

            //服務描述信息
            this.serviceInstaller1.Description = "健康卡服務";
            //服務名稱和前面設置必須相同
            this.serviceInstaller1.ServiceName = "TestService";
            //設置服務自啓動
            this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
        }
        ILog log = LogManager.GetLogger(typeof(ProjectInstaller));
        /// <summary>
        /// 設置服務安裝之後自動啓動
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
        {
            try
            {
                ServiceController service = new ServiceController(this.serviceInstaller1.ServiceName);
                //啓動服務
                service.Start();
            }
            catch (Exception ex)
            {
                log.Error("服務啓動失敗:" + ex);
            }
        }

二、 安裝卸載服務

1.  安裝服務

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil  JKKService.exe
pause

2. 卸載服務

net stop JKKService
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil /u  JKKService.exe
pause

三、常用功能代碼

1. 實時監控(每秒執行一次)
        System.Timers.Timer timer1;
        public UpdatePreDischarge()
        {
            InitializeComponent();
            InitService();
            //記錄所有未捕獲的異常
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }
        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                Exception ex = e.ExceptionObject as Exception;
                string exmsg = "發生異常:" + ex.Message + "詳細信息如下:"
                                    + Environment.NewLine + "[InnerException]" + ex.InnerException
                                    + Environment.NewLine + "[Source]" + ex.Source
                                    + Environment.NewLine + "[TargetSite]" + ex.TargetSite
                                    + Environment.NewLine + "[StackTrace]" + ex.StackTrace;
                SetLog(exmsg);
            }
            catch { }
        }


        /// <summary>
        /// 初始化服務參數
        /// </summary>
        private void InitService()
        {
            base.AutoLog = false;
            base.CanShutdown = true;
            base.CanStop = true;
            base.CanPauseAndContinue = true;
            //服務名稱,設置不一致會產生 1083 錯誤!
            base.ServiceName = "UpdatePreDischarge";
        }


        protected override void OnStart(string[] args)
        {
            timer1 = new System.Timers.Timer();
            timer1.Interval = 1000;  //設置計時器事件間隔執行時間
            //timer1.AutoReset = false;//設置定時器執行完畢之後,再調用timer1.Start();執行下一次。
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
            timer1.Enabled = true;
        }


        private object obj = new object();
        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            lock (obj)
            {
                //實時操作方法
                TimeingExecution();
            }
        }


        /// <summary>
        /// 實時操作方法
        /// </summary>
        private void TimeingExecution()
        {
        }


        protected override void OnStop()
        {
            timer1.Enabled = false;
        }


        #region 記錄日誌
        /// <summary>
        /// 記錄日誌
        /// </summary>
        /// <param name="str"></param>
        public static void SetLog(string str)
        {
            //string log = ConfigurationManager.AppSettings["logPath"];
            string log = System.Windows.Forms.Application.StartupPath + "\\log.txt";
            if (System.IO.File.Exists(log))
            {
                //如果log大於100k,則刪除此文件重新創建
                if (new System.IO.FileInfo(log).Length > 1024 * 100)
                {
                    System.IO.File.Delete(log);
                }
            }
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(log, true))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss  ") + str);
            }
        }
        #endregion


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