Home > C# > สร้าง Windows Service ด้วย C#

สร้าง Windows Service ด้วย C#

ธันวาคม 15th, 2008

เป็นการ 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 ด้วยวิธี “installutil.exe C:\project\WindowsService1\bin\WindowsService1.exe” และใช้ “installutil.exe /u” ในการเอา service ออก

คุณสามารถดูผลของ service ว่าได้ติดตั้งไว้แล้วจาก Computer Management ในส่วนของ services

C#

  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.