C# 如何在收到自定义命令时设置Topshelf?

C# 如何在收到自定义命令时设置Topshelf?,c#,topshelf,C#,Topshelf,我正在使用Topshelf创建一个windows服务(ServiceClass),我正在考虑使用WhenCustomCommandReceived发送自定义命令 HostFactory.Run(x => { x.EnablePauseAndContinue(); x.Service<ServiceClass>(s => { s.ConstructUsing(name => new ServiceClass(path));

我正在使用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();
});
HostFactory.Run(x=>
{
x、 启用PauseandContinue();
x、 服务(s=>
{
s、 ConstructUsing(name=>newserviceclass(path));
s、 开始时(tc=>tc.Start());
s、 停止时(tc=>tc.Stop());
s、 使用时(tc=>tc.Pause());
s、 当继续时(tc=>tc.Resume());
s、 WhenCustomCommandReceived(tc=>tc.ExecuteCustomCommand());
});
x、 RunAsLocalSystem();
x、 SetDescription(“服务名称”);
x、 SetDisplayName(“服务名称”);
x、 SetServiceName(“ServiceName”);
x、 StartAutomatically();
});
但是,我在WhenCustomCommandReceived行上收到一个错误:

委托“Action”不接受1个参数

签名是

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

我的ServiceClass:public void start()中已经有了启动、停止、暂停等方法。有人能告诉我如何设置操作的正确方向吗?谢谢

因此,正如您在方法签名中所看到的,
操作
包含三个参数,而不仅仅是一个参数。这意味着您需要将其设置为:

s.WhenCustomCommandReceived((tc,hc,command) => tc.ExecuteCustomCommand());
s.WhenCustomCommandReceived((tc,hc,command) => tc.ExecuteCustomCommand(command));
本例中有趣的参数是
command
,它的类型为
int
。这是发送到服务的命令号

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

s.WhenCustomCommandReceived((tc,hc,command) => tc.ExecuteCustomCommand());
s.WhenCustomCommandReceived((tc,hc,command) => tc.ExecuteCustomCommand(command));
服务类中

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
根据,命令值必须介于128和256之间


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

谢谢!解决了我的问题。今天学到了一些新东西。使用topshelf是否可以从cmd.exe发送命令?比如>myservice.exe 128?