Start, Stop and Restart Windows Service using C#

You can start, stop and restart a windows service programmatically in C# using .NET build-in class ServiceController. To use ServiceController class, you need to add the namespace “System.ServiceProcess“.

Summary

Start Windows Service using C#

Use the below C# method to start a service by passing service name as argument. This function start the given windows service and waits until the service is running or until given timeout occurs.

public static void StartService(string serviceName)
{
    ServiceController service = new ServiceController(serviceName);
    // Wait Timeout to get running status
    TimeSpan timeout = TimeSpan.FromMinutes(1);
    if (service.Status != ServiceControllerStatus.Running)
    {
        // Start Service
        service.Start();
        service.WaitForStatus(ServiceControllerStatus.Running, timeout);
    }
    else
    {
        // Service already started;
    }
}

Stop Windows Service using C#

Use the below C# method to stop a service by passing service name as argument. This function stop the given windows service and waits until the service is stopped or until given timeout occurs.

public static void StopService(string serviceName)
{
    ServiceController service = new ServiceController(serviceName);
    // Wait Timeout to get stopped status
    TimeSpan timeout = TimeSpan.FromMinutes(1);
    if (service.Status != ServiceControllerStatus.Stopped)
    {
        // Stop Service
        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
    }
    else
    {
        // Service already stopped;
    }
}

Restart Windows Service using C#

There is no direct C# function to restart a service, so, we need do it by two step process, first stop the given service and start the service again. Use the below C# method to restart a service by passing service name as argument. You can give some extra timeout if your service takes more time to stop or start.

public static void RestartService(string serviceName)
{
    ServiceController service = new ServiceController(serviceName);
    TimeSpan timeout = TimeSpan.FromMinutes(1);
    if (service.Status != ServiceControllerStatus.Stopped)
    {
        // Stop Service
        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
    }
    //Restart service
    service.Start();
    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}

Advertisement

1 thought on “Start, Stop and Restart Windows Service using C#”

Leave a Comment