Windows Service in C# | Start, Stop, Pause, Resume, Restart code

The Windows Service in C#, the System.ServiceProcess namespace of System.ServiceProcess.ServiceController.dll has the ServiceController class which can be used to operate with windows services. In this article, learn how to Start, Stop, Pause, Resume and Restart Windows Service in C#.


Start, Stop, Pause, Resume and Restart Windows Service in C#:

Microsoft Windows services are formerly known as NT services. Microsoft Windows services enable us to create long-running executable applications that run in their own Windows sessions. These services can also be started, stopped, paused, or restarted programmatically by the external code.
You can see how you can start, stop, restart, pause, and resume windows service through C# in the below example.

Note: Always make sure to run the application in Administrator mode to start the windows service. Otherwise, your application may encounter a security exception.

How to start Windows service in C#?

/// 
/// Function to start the windows service.
/// 
/// the service name
/// the wait interval
private static void StartService(string serviceName, int nWaitTime)
{
    // Create the service controller instance for the 'serviceName'.
    ServiceController service = new ServiceController(serviceName);
    try
    {
        // Convert the milliseconds into TimeSpan object.
        TimeSpan timeout = TimeSpan.FromMilliseconds(nWaitTime);

        // Start the windowss service.
        service.Start();

        // Wait for the windows service to start until the 'timeout' period. 
        service.WaitForStatus(ServiceControllerStatus.Running, timeout);
    }
    catch (System.ServiceProcess.TimeoutException ex)
    {
        // This exception is thrown when a specified timeout has expired. 
        // For instance, if the service is not started with the specified timeout interval, then TimeOutException occurred.
        // It is recommended to know the actual time taken to start the service before setting the timeout parameter.
    }
}

How to Stop Windows Service in C#?

/// 
/// Function to stop the windows service.
/// 
/// the service name
/// the wait interval
private static void StopService(string serviceName, int nWaitTime)
{
    // Create the service controller instance for the 'serviceName'.
    ServiceController service = new ServiceController(serviceName);
    try
    {
        // Convert the milliseconds into TimeSpan object.
        TimeSpan timeout = TimeSpan.FromMilliseconds(nWaitTime);

        // Check whether the service can be stopped. This flag will return false if service is not started.
        if (service.CanStop)
        {
            // Stop the windows service.
            service.Stop();
        }

        // Wait for the windows service to stop until the 'timeout' period. 
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
    }
    catch (System.ServiceProcess.TimeoutException ex)
    {
        // This exception is thrown when a specified timeout has expired. 
        // For instance, if the service is not stopped with the specified timeout interval, then TimeOutException occurred.
        // It is recommended to know the actual time taken to stop the service before setting the timeout parameter.
    }
}

How to Restart Windows Service in C#?

/// 
/// Function to restart the windows service.
/// 
/// the service name
/// the wait interval
private static void RestartService(string serviceName, int nWaitTime)
{
    // Stop the windows service
    StopService(serviceName, nWaitTime);

    // Introduce delay for 100 ms.
    Thread.Sleep(100);

    // Start the windows service.
    StartService(serviceName, nWaitTime);
}

How to Pause Windows Service in C#?

/// 
/// Function to resume the windows service.
/// 
/// the service name
/// the wait interval
private static void ResumeService(string serviceName, int nWaitTime)
{
    // Create the service controller instance for the 'serviceName'.
    ServiceController service = new ServiceController(serviceName);
    try
    {
        // Convert the milliseconds into TimeSpan object.
        TimeSpan timeout = TimeSpan.FromMilliseconds(nWaitTime);

        // Check whether the windows service can be paused/continue
        if (service.CanPauseAndContinue)
        {
            // resume the windowss service.
            service.Continue();
        }

        // Wait for the windows service to paused until the 'timeout' period. 
        service.WaitForStatus(ServiceControllerStatus.Paused, timeout);
    }
    catch (System.ComponentModel.Win32Exception ex)
    {
        // Handle the exception here.
    }
}

How to Resume Windows Service in C#?

/// 
/// Function to pause the windows service.
/// 
/// the service name
/// the wait interval
private static void PauseService(string serviceName, int nWaitTime)
{
    // Create the service controller instance for the 'serviceName'.
    ServiceController service = new ServiceController(serviceName);
    try
    {
        // Convert the milliseconds into TimeSpan object.
        TimeSpan timeout = TimeSpan.FromMilliseconds(nWaitTime);

        // Check whether the windows service can be paused/continue
        if (service.CanPauseAndContinue)
        {
            // Pause the windowss service.
            service.Pause();
        }

        // Wait for the windows service to paused until the 'timeout' period. 
        service.WaitForStatus(ServiceControllerStatus.Paused, timeout);
    }
    catch (System.ComponentModel.Win32Exception ex)
    {
        // Handle the exception here.
    }
}

Complete source code:

using System;
using System.ServiceProcess;
using System.Text;
using System.Threading;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Set the name of choice of your windows service name intended to start.
            string serviceName = "MyService";

            // Set the wait time in miliseconds.
            // It is recommended to know the actual time taken to start/stop the service, before setting the timeout parameter.
            int nWaitTime = (60 * 1000); //1 minute
            
            // Start the windows service.
            StartService(serviceName, nWaitTime);

            // Stop the windows service
            StopService(serviceName, nWaitTime);

            // Restart the windows service
            RestartService(serviceName, nWaitTime);

            // Pause the windows service.
            PauseService(serviceName, nWaitTime);

            // Resume the windows service. 
            ResumeService(serviceName, nWaitTime);
        }

        /// 
        /// Function to resume the windows service.
        /// 
        /// the service name
        /// the wait interval
        private static void ResumeService(string serviceName, int nWaitTime)
        {
            // Create the service controller instance for the 'serviceName'.
            ServiceController service = new ServiceController(serviceName);
            try
            {
                // Convert the milliseconds into TimeSpan object.
                TimeSpan timeout = TimeSpan.FromMilliseconds(nWaitTime);

                // Check whether the windows service can be paused/continue
                if (service.CanPauseAndContinue)
                {
                    // resume the windowss service.
                    service.Continue();
                }

                // Wait for the windows service to paused until the 'timeout' period. 
                service.WaitForStatus(ServiceControllerStatus.Paused, timeout);
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                // Handle the exception here.
            }
        }

        /// 
        /// Function to pause the windows service.
        /// 
        /// the service name
        /// the wait interval
        private static void PauseService(string serviceName, int nWaitTime)
        {
            // Create the service controller instance for the 'serviceName'.
            ServiceController service = new ServiceController(serviceName);
            try
            {
                // Convert the milliseconds into TimeSpan object.
                TimeSpan timeout = TimeSpan.FromMilliseconds(nWaitTime);

                // Check whether the windows service can be paused/continue
                if (service.CanPauseAndContinue)
                {
                    // Pause the windowss service.
                    service.Pause();
                }

                // Wait for the windows service to paused until the 'timeout' period. 
                service.WaitForStatus(ServiceControllerStatus.Paused, timeout);
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                // Handle the exception here.
            }
        }

        /// 
        /// Function to start the windows service.
        /// 
        /// the service name
        /// the wait interval
        private static void StartService(string serviceName, int nWaitTime)
        {
            // Create the service controller instance for the 'serviceName'.
            ServiceController service = new ServiceController(serviceName);
            try
            {
                // Convert the milliseconds into TimeSpan object.
                TimeSpan timeout = TimeSpan.FromMilliseconds(nWaitTime);

                // Start the windowss service.
                service.Start();

                // Wait for the windows service to start until the 'timeout' period. 
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
            catch (System.ServiceProcess.TimeoutException ex)
            {
                // This exception is thrown when a specified timeout has expired. 
                // For instance, if the service is not started with the specified timeout interval, then TimeOutException occurred.
                // It is recommended to know the actual time taken to start the service before setting the timeout parameter.
            }
        }

        
        /// 
        /// Function to stop the windows service.
        /// 
        /// the service name
        /// the wait interval
        private static void StopService(string serviceName, int nWaitTime)
        {
            // Create the service controller instance for the 'serviceName'.
            ServiceController service = new ServiceController(serviceName);
            try
            {
                // Convert the milliseconds into TimeSpan object.
                TimeSpan timeout = TimeSpan.FromMilliseconds(nWaitTime);

                // Check whether the service can be stopped. This flag will return false if service is not started.
                if (service.CanStop)
                {
                    // Stop the windows service.
                    service.Stop();
                }

                // Wait for the windows service to stop until the 'timeout' period. 
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
            }
            catch (System.ServiceProcess.TimeoutException ex)
            {
                // This exception is thrown when a specified timeout has expired. 
                // For instance, if the service is not stopped with the specified timeout interval, then TimeOutException occurred.
                // It is recommended to know the actual time taken to stop the service before setting the timeout parameter.
            }
        }

        /// 
        /// Function to restart the windows service.
        /// 
        /// the service name
        /// the wait interval
        private static void RestartService(string serviceName, int nWaitTime)
        {
            // Stop the windows service
            StopService(serviceName, nWaitTime);

            // Introduce delay for 100 ms.
            Thread.Sleep(100);

            // Start the windows service.
            StartService(serviceName, nWaitTime);
        }
    }
}


– Article ends here –

If you have any questions, please feel free to share your questions or comments on the comment box below.

Recommended:   Simulating Blue Screen Of Death - BOSD error in C#
Share this:
We will be happy to hear your thoughts

Leave a reply

Troubleshootyourself
Logo