如何使用WhenCustomCommandReceived设置Topshelf?

Let*_*der 2 c# topshelf

我正在使用Topshelf创建一个Windows服务(ServiceClass),我正在考虑使用WhenCustomCommandReceived发送自定义命令.

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();
});
Run Code Online (Sandbox Code Playgroud)

但是,我在WhenCustomCommandReceived行上收到错误:

委托'Action <ServiceClass,HostControl,int>'不带1个参数

签名是

ServiceConfigurator<ServiceClass>.WhenCustomCommandReceived(Action<ServiceClass, HostControl, int> customCommandReceived)
Run Code Online (Sandbox Code Playgroud)

我已经有了在我的ServiceClass中启动,停止,暂停的方法:public void Start()等.有人能指出我如何设置Action的正确方向吗?谢谢!

Yac*_*sad 5

因此,正如您在方法的签名中看到的那样,Action需要三个参数,而不仅仅是一个参数.这意味着你需要像这样设置它:

s.WhenCustomCommandReceived((tc,hc,command) => tc.ExecuteCustomCommand());
Run Code Online (Sandbox Code Playgroud)

在这种情况下,有趣的参数command是类型int.这是发送到服务的命令编号.

您可能希望更改ExecuteCustomCommand方法的签名以接受此类命令:

s.WhenCustomCommandReceived((tc,hc,command) => tc.ExecuteCustomCommand(command));
Run Code Online (Sandbox Code Playgroud)

并在ServiceClass:

public void ExecuteCustomCommand(int command)
{
    //Handle command
}
Run Code Online (Sandbox Code Playgroud)

这允许您根据收到的命令采取不同的行动.

要测试向服务发送命令(来自另一个C#项目),您可以使用以下代码:

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

根据此MSDN参考,命令值必须介于128和256之间.

确保在测试项目中引用System.ServiceProcess程序集.