c# Windows 服務創建與操作

一、創建window服務

1、新建項目-->選擇Windows服務。默認生成文件包括Program.cs,Service1.cs

2、在Service1.cs添加如下代碼:

  1.        System.Timers.Timer timer1;  //計時器

        public Service1()

        {

            InitializeComponent();

        }

        protected override void OnStart(string[] args)  //服務啓動執行

        {

            timer1 = new System.Timers.Timer();

  1.             timer1.Interval = 3000;  //設置計時器事件間隔執行時間

            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);

            timer1.Enabled = true;

        }

        protected override void OnStop()  //服務停止執行

        {

            this.timer1.Enabled = false;

        }

 

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)

        {

            //執行SQL語句或其他操作

        }

 

二、添加window服務安裝程序

1、打開Service1.cs【設計】頁面,點擊右鍵,選擇【添加安裝程序】,會出現serviceInstaller1和serviceProcessInstaller1兩個組件

2、將serviceProcessInstaller1的Account屬性設爲【LocalSystem】, serviceInstaller1的StartType屬性設爲【Automatic】,ServiceName屬性可設置服務名稱,此後在【管理工具】--》【服務】中即顯示此名稱

3、ProjectInstaller.cs文件,在安裝服務後一般還需手動啓動(即使上述StartType屬性設爲【Automatic】),可在ProjectInstaller.cs添加如下代碼實現安裝後自動啓動

    public ProjectInstaller()
        {
            InitializeComponent();
            this.Committed += new InstallEventHandler(ProjectInstaller_Committed);   
        }

        private void ProjectInstaller_Committed(object sender, InstallEventArgs e)
        {
            //參數爲服務的名字
            System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("服務名稱");
            controller.Start();
        }   

 

三、安裝、卸載window服務

1、輸入cmd(命令行),輸入cd  C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727

2、安裝服務(項目生成的exe文件路徑)

  InstallUtil "E:/WindowsService1/bin/Debug/WindowsService1.exe"(服務所在的路徑)

3、卸載服務

  InstallUtil  /u "E:/WindowsService1/bin/Debug/WindowsService1.exe"

四、查看window服務

控制面板-->管理工具-->服務,可在此手動啓動,停止服務

五、調試window服務

1. 在程序中打斷點調試,調試服務時服務必須已啓動(管理工具-->服務)

2、通過【事件查看器】查看服務啓動與停止信息及時間等

3、直接在程序中調試(菜單-->調試-->附加進程-->服務名(這裏的服務名是項目名稱,不是ServiceName屬性自定義的名稱,所以建議自定義名稱和項目名稱保持一致,另外需勾選【顯示所有用戶的進程】才能看到服務名)-->附加

 

發佈了123 篇原創文章 · 獲贊 14 · 訪問量 29萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章