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

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 17:31:33
dtb

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)
    {
        // ...
    }
}
Aliostad

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!