Restarting Windows services in C#

It’s dead simple to restart a Windows service in C#. I’m a little shocked at how easy it is actually, given some of the other things I’ve found to be so ugly about the language.

public void RestartService(string name)
{
    ServiceController service = new ServiceController(name);
    service.Stop();
    Thread.Sleep(2500);
    service.Start();
    Thread.Sleep(2500);
}

You guessed it: “name” is the name of the service to restart. It must exactly match the actual service name or bad things will happen. I added the sleeps for good measure. They may or may not be needed depending on how responsive you want the service to be immediately after restarting.

Now if only C# made it this easy to restart a UNIX process…