I found the following code on the Internet:

private static ServiceController ser { get; set; } using (ser = new ServiceController("MpsSvc")) { ser.Start(); label.Visible = true; label.Text = "Служба запущена!"; ser.Close(); } 

Sometimes it works, sometimes it doesn't.

Can the service existence check + service start check be screwed to the above code (if the service is stopped to start)

Should I use get;set; for such purposes?


Redid so correct if not correct)

  private void StopService_Click(object sender, EventArgs e) { using (var serviceController = new ServiceController("sevice")) { if (CheckService.CheckIfServiceExists("sevice")) { serviceController.Stop(); serviceController.WaitForStatus(ServiceControllerStatus.Stopped); label.Visible = true; label2.Text = "Служба остановлена"; StopService.Visible = false; StartService.Visible = true; } } } 

The first time passes normally, the next one says that the service could not be stopped / started (although the service is running before stopping)

What is the reason?

    1 answer 1

    You can check the status of a service at any time using ServiceController.Status

    To check the existence of a service, get a list of existing services and check the presence of the service you require in this list:

     public bool CheckIfServiceExists(string serviceName) { var services = ServiceController.GetServices(); return services.Any(s => s.ServiceName == serviceName); } 

    Should I use get; set; for such purposes?

    The question is unclear. If I were you, I would remove this property altogether and design it as a local variable.

    To check whether the service has really started / stopped, use the ServiceController.WaitForStatus() method. Send ServiceControllerStatus.Running to wait for the service to start or ServiceControllerStatus.Stopped to wait for the service to stop after calling the ServiceController.Start() and ServiceController.Stop() functions, respectively.

    Example of starting the service:

     using(var serviceController = new ServiceController(ИмяСервиса)) { serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running); } 
    • In the form of a local variable? - GooliveR
    • And what's stopping you from doing this? Why should you keep it as a private property of a class, especially when you dispose it? - MihailPw
    • one
      Added an example of starting a service. Consider that serviceController.WaitForStatus() can be a long process, so I would advise you to pre-wrap the method in a task. - MihailPw
    • And if you add a list of services in List<string> , and after how to use? I mean, is WaitForStatus required? WaitForStatus I want to stop services (list of services)? - GooliveR