初識Windows服務

來源:互聯網
上載者:User

標籤:

1.建立Windows服務  

 

 

2.切換到程式碼檢視,拷入如下代碼

該服務以10S的間隔建立 d:/1.txt 檔案

 

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Diagnostics;using System.IO;using System.Linq;using System.ServiceProcess;using System.Text;using System.Threading.Tasks;using System.Timers; namespace WindowsServiceTest{ public partial class Service1 : ServiceBase{public Service1(){InitializeComponent();}protected override void OnStart(string[] args){//服務開啟執行代碼StartDoSomething();}protected override void OnStop(){//服務結束執行代碼}protected override void OnPause(){//服務暫停執行代碼base.OnPause();}protected override void OnContinue(){//服務恢複執行代碼base.OnContinue();}protected override void OnShutdown(){//系統即將關閉執行代碼base.OnShutdown();}private void StartDoSomething(){System.Timers.Timer timer = new System.Timers.Timer(10000); //間隔10秒timer.AutoReset = true;timer.Enabled = false; //執行一次timer.Elapsed += new ElapsedEventHandler(WriteSomething);timer.Start();}private void WriteSomething(object source, System.Timers.ElapsedEventArgs e){FileStream fs = null;try{fs = new FileStream("d:/1.txt", FileMode.OpenOrCreate);string strText = @"以10秒的間隔重複建立該檔案,若已有同名檔案,則保持不變";//獲得位元組數組byte[] data = new UTF8Encoding().GetBytes(strText);//開始寫入fs.Write(data, 0, data.Length);//清空緩衝區、關閉流fs.Flush();fs.Close();fs.Dispose();}catch{}finally{if (fs != null){fs.Close();fs.Dispose();}}}}}

  

3.添加安裝程式並設定控制項屬性1.在設計頁面右鍵,選擇添加安裝程式

 

 

 

 

2.將左上方第一個控制項的Account屬性設定為LocalService

 

 

3.可以自行修改第二個控制項的ServiceName(服務名稱,不可和系統已有的衝突),StartType設定為Automatic

 

 

4.編譯項目

1.產生解決方案(Ctrl+Shift+B),編譯完成後會產生對應的xxx.exe

 

2.找到系統裡面InstallUtil的安裝目錄 例如 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe  實在找不到就用Everything吧

3.Win+R CMD  cd 跳轉到InstallUtil的安裝路徑,運行如下命令  InstallUtil.exe+空格+4.1產生的exe的目錄

    cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

    InstallUtil.exe E:\GitVSTest\WindowsServiceTest\WindowsServiceTest\bin\Debug\WindowsServiceTest.exe

 

 

5.啟動服務在電腦-管理-服務和應用程式-服務 裡面找到剛才編譯的服務,右鍵啟動即可 6.修改服務1.在服務裡面,停止對應服務 2.修改原始碼並再次產生解決方案(Ctrl+Shift+B)3.再次啟動服務7.卸載服務卸載服務啟動並執行命名和4.3 類似依然是在InstallUtil 目錄下,不過是運行 InstallUtil.exe /u 產生的exe的目錄例如:C:\Windows\Microsoft.NET\Framework64\v4.0.30319>InstallUtil.exe /u E:\GitVSTest\WindowsServiceT2\WindowsServiceT2\bin\Debug\WindowsServiceT2.exe

初識Windows服務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.