2009-07-17 80 views
3

我想創建一個控制檯EXE應用程序,它可以作爲一個獨立的應用程序以及一個Windows服務運行。有可能嗎?實際上使用svchost的好處是什麼?如何創建一個獨立的exe應用程序的Windows服務?

+0

可能的重複 - http://stackoverflow.com/questions/355579/my-exe-runs-fine-by-itself-but-does-nothing-when-loaded-by-a-service&http:// stackoverflow.com/questions/165951/how-can-i-run-a-cli-application-as-a-windows-service – ChrisF 2009-07-17 10:22:32

回答

14

重寫你的Windows服務的主要方法是這樣,這將是控制檯應用程序,如果你有parametr -c運行,是不會忘了改項目類型從項目的屬性窗口安慰

public static void Main(string[] args) 
{ 
     Service service = new Service(); 
     if (args.Contains("-c", StringComparer.InvariantCultureIgnoreCase) || args.Contains("-console", StringComparer.InvariantCultureIgnoreCase)) 
     { 
      service.StartService(args); 
      Console.ReadLine(); 
      service.StopService(); 
      return; 
     } 
     ServiceBase[] ServicesToRun = new ServiceBase[] 
            { 
             service 
            }; 
     ServiceBase.Run(ServicesToRun);   
    } 

StartService和StopService只是調用服務的被忽略的OnStart和OnStop方法

+0

+1,我的回答刪除:) – 2009-07-17 10:28:24

2

這種情況的最佳方法是考慮組件的概念。

你的策略應該是開發一個你需要的所有邏輯的DLL。

之後,您將構建使用該DLL的控制檯應用程序和Windows服務。

組件的概念和重用它們的可能性是微不足道的,也是很明智的。

當你需要改變你的邏輯時,你只需要改變DLL,並用舊的替換。你不需要任何特殊的部署。

相關問題