How to send a custom command to a .NET windows Service from .NET code?

后端 未结 2 1021
生来不讨喜
生来不讨喜 2020-11-30 22:25

As in the following link, one can stop, start, and \"stop, then start\" a service using C# code.

http://www.csharp-examples.net/restart-windows-service/

I ha

相关标签:
2条回答
  • 2020-11-30 22:52

    The usual means of communicating with external processes in windows are:

    1. Named pipes
    2. Sockets
    3. COM's GetObject to get a reference to an object and then calling its methods over the exposed interface.

    The first two have been exposed as WCF so that is the way to go. Third one does not seem relevant to your situation and is old.

    If you need to run your commands from the same machine you can use named pipes but hardening has made it very difficult and troublesome. Otherwise use WCF's TCP named binding.

    0 讨论(0)
  • 2020-11-30 23:05

    You can send "commands" to a service using ServiceController.ExecuteCommand:

    const int SmartRestart = 222;
    
    var service = new System.ServiceProcess.ServiceController("MyService");
    service.ExecuteCommand(SmartRestart);
    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
    

    You'll need to add a Reference to the System.ServiceProcess.dll assembly.

    The service can react to the command by overriding ServiceBase.OnCustomCommand:

    protected override void OnCustomCommand(int command)
    {
        if (command == SmartRestart)
        {
            // ...
        }
    }
    
    0 讨论(0)
提交回复
热议问题