Restart a service with dependent services?

后端 未结 3 1996
广开言路
广开言路 2021-02-20 07:36

Starting with a csharp-example and duly noting related SO questions ( Restart a windows services from C# and Cannot restart a Service) and various other questions relating to

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-20 07:50

    Please notice that ServiceController.Stop() stops 'dependent' services and ServiceController.Start() starts 'dependent on' services - thus after stopping the service you'll only need to start services that are dependency tree's leaves.

    Assuming no cyclic dependencies are allowed, the following code gets services that need to be started:

        private static void FillDependencyTreeLeaves(ServiceController controller, List controllers)
        {
            bool dependencyAdded = false;
            foreach (ServiceController dependency in controller.DependentServices)
            {
                ServiceControllerStatus status = dependency.Status;
                // add only those that are actually running
                if (status != ServiceControllerStatus.Stopped && status != ServiceControllerStatus.StopPending)
                {
                    dependencyAdded = true;
                    FillDependencyTreeLeaves(dependency, controllers);
                }
            }
            // if no dependency has been added, the service is dependency tree's leaf
            if (!dependencyAdded && !controllers.Contains(controller))
            {
                controllers.Add(controller);
            }
        }
    

    And with a simple method (e.g. extension method):

        public static void Restart(this ServiceController controller)
        {
            List dependencies = new List();
            FillDependencyTreeLeaves(controller, dependencies);
            controller.Stop();
            controller.WaitForStatus(ServiceControllerStatus.Stopped);
            foreach (ServiceController dependency in dependencies)
            {
                dependency.Start();
                dependency.WaitForStatus(ServiceControllerStatus.Running);
            }
        }
    

    You can simply restart a service:

        using (ServiceController controller = new ServiceController("winmgmt"))
        {
            controller.Restart();
        }
    

    Points of interest:

    For code clearity I didn't add:

    • timeouts
    • error-checking

    Please notice, that the application may end up in a strange state, when some services are restarted and some are not...

提交回复
热议问题