How to enable C # to start Windows service and shut down
It is believed that many inexperienced people don't know what to do about how to start Windows service and shut down in C#. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
What are the steps and classes that C # uses to start the Windows service and close the instance implementation? Let's take a look at the implementation:
C # controls the startup and shutdown of Windows services
/ /. Using System.ServiceProcess; / /. / Restart windows service / the windows service display name / If the restart successfully / return true else return false public static bool RestartWindowsService (string serviceName) {bool bResult = false; try {try {/ / C # start Windows service and shut down StopWindowsService (serviceName); Thread.Sleep (1000);} catch (Exception ex) {StartWindowsService (serviceName) Thread.Sleep (1000); StopWindowsService (serviceName); Thread.Sleep (1000); Console.WriteLine (ex.Message);} try {StartWindowsService (serviceName); Thread.Sleep (1000);} catch (Exception ex) / / C# start Windows service and shut down {StopWindowsService (serviceName); Thread.Sleep (1000); StartWindowsService (serviceName); Thread.Sleep (1000) Console.WriteLine (ex.Message);} bResult = true;} catch (Exception ex) {bResult = false; throw ex;} return bResult } / / C # start the Windows service and close / Start windows service / the windows service display name / If the start successfully / return true else return false public static bool StopWindowsService (string serviceName) {ServiceController [] scs = ServiceController.GetServices (); bool bResult = false Foreach (ServiceController sc in scs) {if (sc.DisplayName = = serviceName) {try {sc.WaitForStatus (ServiceControllerStatus.Running, TimeSpan.FromSeconds (30)); sc.Stop (); bResult = true;} catch (Exception ex) {bResult = false; throw ex;}} return bResult } / / C # start Windows service and close / Stop windows service / the windows / / service display name / If the stop successfully / return true else return false public static bool StartWindowsService (string serviceName) {ServiceController [] scs = ServiceController.GetServices (); bool bResult = false Foreach (ServiceController sc in scs) {if (sc.DisplayName = = serviceName) {try {sc.WaitForStatus (ServiceControllerStatus.Stopped, TimeSpan.FromSeconds (30)); sc.Start (); bResult = true;} catch (Exception ex) {bResult = false; throw ex;}} / / C # start Windows service and close} return bResult;}
C # starts Windows service and shuts down the concrete implementation to introduce to you here, hope to help you to understand and learn C # to start Windows service and shut down.
After reading the above, do you know how to start and shut down Windows services in C #? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!