標籤:config [] .net lock src 自己的 步驟 writer logs
學然後知不足 教然後知困。
沒做過windows service開發時,感覺很難,無從下手。再網看了些例子,加上自己的理解,寫下開發步驟。
開發步驟
建立windows service
添加服務,發表後將再自己的電腦的 服務管理 查看到
partial class MyService : ServiceBase { Timer timer1; public MyService() { InitializeComponent(); } protected override void OnStart(string[] args) { // TODO: Add code here to start your service. using (StreamWriter sw = File.AppendText(@"D:\\log2.txt")) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Start."); } timer1 = new Timer(); timer1.Interval = 2000; timer1.Elapsed += (sender, e) => { using (StreamWriter sw = File.AppendText(@"D:\\log2.txt")) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Countue..."); } }; timer1.Start(); } protected override void OnStop() { // TODO: Add code here to perform any tear-down necessary to stop your service. using (StreamWriter sw = File.AppendText(@"D:\\log2.txt")) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Stop."); } } }
- 添加服務安裝程式(這是vs給提供的方便操作),可以發表多個服務。
右擊,點擊Add Installer
,自動產生類ProjectInstaller
。大家可以看下vs自動產生的類ProjectInstaller.Designer.cs
檔案
private void InitializeComponent() { this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); //設定服務安裝資訊 this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService; this.serviceProcessInstaller1.Password = null; this.serviceProcessInstaller1.Username = null; //要安裝的服務(保證與你的服務名一致,可添加多個) this.serviceInstaller1.ServiceName = "MyService"; //服務加入 this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.serviceProcessInstaller1, this.serviceInstaller1}); }
注意將服務安裝設定為:手動安裝
服務安裝卸載指令碼
Install.bat 檔案:
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe "%~dp0%WindowsServiceTest.exe"pause
Uninstall.bat檔案:
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe -u "%~dp0%WindowsServiceTest.exe"pause
windows服務開發