2015-12-20 57 views
2

我正在使用Topshelf創建一個Windows服務(ServiceClass),我正在考慮使用WhenCustomCommandReceived發送自定義命令。如何使用WhenCustomCommandReceived設置Topshelf?

HostFactory.Run(x => 
{ 
    x.EnablePauseAndContinue(); 
    x.Service<ServiceClass>(s => 
    { 
     s.ConstructUsing(name => new ServiceClass(path)); 
     s.WhenStarted(tc => tc.Start()); 
     s.WhenStopped(tc => tc.Stop()); 
     s.WhenPaused(tc => tc.Pause()); 
     s.WhenContinued(tc => tc.Resume()); 
     s.WhenCustomCommandReceived(tc => tc.ExecuteCustomCommand()); 
    }); 
    x.RunAsLocalSystem(); 
    x.SetDescription("Service Name"); 
    x.SetDisplayName("Service Name"); 
    x.SetServiceName("ServiceName"); 
    x.StartAutomatically(); 
}); 

但是,我越來越對WhenCustomCommandReceived行錯誤:

委託 '行動<服務類,HostControl,int>的' 不拿1個參數

簽名是

ServiceConfigurator<ServiceClass>.WhenCustomCommandReceived(Action<ServiceClass, HostControl, int> customCommandReceived) 

我已經有在我的ServiceClass中啓動,停止,暫停的方法:public void Start()等等。任何人都可以在ho的正確方向指向我w設置操作?謝謝!

回答

4

因此,正如您在該方法的簽名中看到的,Action需要三個參數,而不僅僅是一個。這意味着,你需要設置它是這樣的:

s.WhenCustomCommandReceived((tc,hc,command) => tc.ExecuteCustomCommand()); 

在這種情況下,有趣的參數是command這是int類型。這是發送到服務的命令號碼。

你可能想改變ExecuteCustomCommand方法的簽名接受這樣的命令是這樣的:

s.WhenCustomCommandReceived((tc,hc,command) => tc.ExecuteCustomCommand(command)); 

而在ServiceClass

public void ExecuteCustomCommand(int command) 
{ 
    //Handle command 
} 

這可以讓你以不同的基礎上採取行動你收到的命令。

爲了測試將命令發送到該服務(從另一個C#項目),可以使用以下代碼:

ServiceController sc = new ServiceController("ServiceName"); //ServiceName is the name of the windows service 
sc.ExecuteCommand(255); //Send command number 255 

根據this MSDN reference,命令值必須是128到256之間和

確保在測試項目中引用System.ServiceProcess程序集。

+0

謝謝雅各布!解決了我的問題。今天學到了新東西。 –