我正在使用Topshelf创建一个Windows服务(ServiceClass),我正在考虑使用WhenCustomCommandReceived发送自定义命令.
HostFactory.Run(x => { x.EnablePauseAndContinue(); x.Service(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行上收到错误:
委托'Action
签名是
ServiceConfigurator.WhenCustomCommandReceived(Action customCommandReceived)
我已经有了在我的ServiceClass中启动,停止,暂停的方法:public void Start()等.有人能指出我如何设置Action的正确方向吗?谢谢!
因此,正如您在方法的签名中看到的那样,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
根据此MSDN参考,命令值必须介于128和256之间.
确保在测试项目中引用System.ServiceProcess程序集.