สร้าง Windows Service ด้วย C#
เป็นการ service เพื่อทำงานในลักษณะ background process ตัวอย่างที่เห็นได้ชัดคือพวก
apache, tomcat , fax service ของ microsoft ก็ใช้งานในลักษณะนี้
เริ่มต้นจากการสร้าง windows service
System.IO.StreamWrite file;
protected override void OnStart(string[] args)
{
// create or open the file. Default path is "C:\windows\System32\"
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″; // this must match the ServiceName specified in WindowsService1.
si.DisplayName = “Devhood Tutorial Service”; // this will be displayed in the Services Manager.
this.Installers.Add(si);
spi.Account = System.ServiceProcess.ServiceAccount.LocalSystem; // run under the system account.
spi.Password = null;
spi.Username = null;
this.Installers.Add(spi);
คุณสามารถดูผลของ service ว่าได้ติดตั้งไว้แล้วจาก Computer Management ในส่วนของ services
ความเห็นล่าสุด