2010-08-13 53 views
1

我得到了下面的代碼從http://tech.einaregilsson.com/2007/08/15/run-windows-service-as-a-console-program/如何時通知服務站要求

當在控制檯模式下運行,我想通知當請求服務停止,而不是等待用戶輸入。 (我的意思是在這裏用戶請求通過Ctrl + C或關閉控制檯停止程序)

當作爲服務工作時,OnStop被停止請求調用是微不足道的,但我怎樣才能實現一種解決方法,以便我也可以在控制檯模式下工作時會收到通知。

那麼是否有任何事件可以訂閱通知或任何成員函數等?

在此先感謝。
最好的問候,
-Victor

using System; 
using System.ServiceProcess; 
public partial class DemoService : ServiceBase 
{ 
    static void Main(string[] args) 

    { 
     DemoService service = new DemoService(); 

     if (Environment.UserInteractive) // Console mode 
     { 
      service.OnStart(args); 
      Console.WriteLine("Press any key to stop program"); 

      Console.Read(); 

      service.OnStop(); 
     } 
     else 
     { 
      ServiceBase.Run(service); 
     } 
    } 

    public DemoService() 
    { 
     InitializeComponent(); 
    } 

    protected override void OnStart(string[] args) 
    { 
     // TODO: Add code here to start your service. 
    } 
    protected override void OnStop() 
    { 
     // TODO: Add code here to perform any tear-down 

     //necessary to stop your service. 
    } 
} 
+0

我想你可以使用類似看門狗的模式。以前沒有用過這個東西。 – Warty 2010-08-13 11:53:27

回答