2009-04-15 137 views
3

什麼是運行Windows服務作爲控制檯的最佳方式運行Windows服務?在控制檯

我目前的想法是傳遞一個「/ exe」參數並完成windows服務的工作,然後調用Application.Run()。

我這樣做的原因是爲了更好地調試Windows服務,並允許代碼更容易分析。該服務基本上託管.NET遠程對象。

回答

6

這是我要做的事。爲我提供與控制檯應用程序和服務相同的.exe文件。要作爲控制檯應用程序啓動,它需要命令行參數-c。

private static ManualResetEvent m_daemonUp = new ManualResetEvent(false); 

[STAThread] 
static void Main(string[] args) 
{ 
    bool isConsole = false; 

    if (args != null && args.Length == 1 && args[0].StartsWith("-c")) { 
     isConsole = true; 
     Console.WriteLine("Daemon starting"); 

     MyDaemon daemon = new MyDaemon(); 

     Thread daemonThread = new Thread(new ThreadStart(daemon.Start)); 
     daemonThread.Start(); 
     m_daemonUp.WaitOne(); 
    } 
    else { 
     System.ServiceProcess.ServiceBase[] ServicesToRun; 
     ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service() }; 
     System.ServiceProcess.ServiceBase.Run(ServicesToRun); 
    } 
} 
+0

我結束了這一點: ThreadPool.QueueUserWorkItem(狀態=> service.DoWork()); new ManualResetEvent(false).WaitOne(); 我讀過使用線程池幾乎總是比明確創建線程更好。 – 2009-04-15 11:17:10

4

代碼項目網站有一個很好的article顯示如何在Visual Studio調試器中運行Windows服務,不需要控制檯應用程序。

2

或者

C:\> MyWindowsService.exe /? 
MyWindowsService.exe /console 
MyWindowsService.exe -console