สร้าง Windows Service ด้วย C#
เป็นการ service เพื่อทำงานในลักษณะ background process ตัวอย่างที่เห็นได้ชัดคือพวก
apache, tomcat , fax service ของ microsoft ก็ใช้งานในลักษณะนี้
เริ่มต้นจากการสร้าง windows service
System.IO.StreamWrite file;
protected override void OnStart(string[] args) { file = new StreamWriter( new FileStream("ServiceTest.log", System.IO.FileMode.Append ) ); this.file.WriteLine("Starting Service"); this.file.Flush(); }
protected override void OnStop() { this.file.WriteLine("Stopping Service"); this.file.Flush(); this.file.Close(); }
จากนั้นให้สร้าง installer class โดยเพิ่ม using System.ServiceProcess; เข้าไปพร้อมโค้ดต่อไปนี้
ServiceInstaller si = new ServiceInstaller();
ServiceProcessInstaller spi = new ServiceProcessInstaller();
si.ServiceName = “Service1″;
si.DisplayName = “Devhood Tutorial Service”;
this.Installers.Add(si);
spi.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
spi.Password = null;
spi.Username = null;
this.Installers.Add(spi);
เพื่อให้โปรแกรมทำงานได้ ต้องทำการติดตั้ง service ด้วยวิธี “installutil.exe C:\project\WindowsService1\bin\WindowsService1.exe” และใช้ “installutil.exe /u” ในการเอา service ออก
คุณสามารถดูผลของ service ว่าได้ติดตั้งไว้แล้วจาก Computer Management ในส่วนของ services
อันนี้เอามาจากเว็บเพื่อนผมเอง http://www.sourcecode.in.th/9M/?p=50
|