Windows Service 是在 Windows OS 下執行的一種常駐程式,網站上也有不少教學說明如何 step-by-step 的開發。如果有興趣也可以參考
How to: Create Windows Services
但是 Windows Service 無法在直接執行,必須要透過 install 才可以執行並看到執行結果,寫起來十分不方便。Google 了一下,發現可以將 Windows Service 改成一個 Console 的程式,在 Debug 時可以在 Console 下執行並將訊息輸出至畫面,待開發完成再包成安裝即可,十分方便。
步驟記錄如下:
1. 建立 Windows Service 專案2. 開啟專案的 properties 畫面, 將 output type 改成 Console Application
3. 開啟 program.cs, 將 Main 函式改成如下:
static void Main(string[] args)
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyConsoleService() };
if (Environment.UserInteractive)
{
Type type = typeof(ServiceBase);
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
MethodInfo method = type.GetMethod("OnStart", flags);
foreach (ServiceBase service in ServicesToRun)
{
method.Invoke(service, new object[] { args });
}
Console.WriteLine("== 結束請按任意鍵 =="); Console.Read();
foreach (ServiceBase service in ServicesToRun)
{
service.Stop();
}
}
else
{
ServiceBase.Run(ServicesToRun);
}
}
~ Keep Coding; Keep Writing
0 意見: