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

后端 未结 2 1020
生来不讨喜
生来不讨喜 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 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)
        {
            // ...
        }
    }
    

提交回复
热议问题