【问题标题】:How to setup Topshelf with WhenCustomCommandReceived?如何使用WhenCustomCommandReceived 设置Topshelf?
【发布时间】:2015-12-20 12:49:21
【问题描述】:

我正在使用 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();
});

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

Delegate 'Action' 不接受 1 个参数

签名是

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

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

【问题讨论】:

    标签: c# topshelf


    【解决方案1】:

    所以,正如您在方法的签名中看到的那样,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 程序集。

    【讨论】:

    • 谢谢雅库布!解决了我的问题。今天学到了一些新东西。
    • 是否可以使用 topshelf 从 cmd.exe 发送命令?喜欢 > myservice.exe 128?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多