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

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 lear 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.
In the below example, you can see how you can start, stop, restart, pause and resume windows service through C#.

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

Starting Windows service:

Stop Windows Service:

Restart Windows Service:

Pause Windows Service:

Resume Windows Service:

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);
        }

        /// <summary>
        /// Function to resume the windows service.
        /// </summary>
        /// <param name="serviceName">the service name</param>
        /// <param name="nWaitTime">the wait interval</param>
        private static void ResumeService(string serviceName, int nWaitTime)
        {
            // Create the service controller instance for the 'serviceName'.
            ServiceController service = new ServiceController(serviceName);
            try
            {
                // Convert the miliseconds 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.
            }
        }

        /// <summary>
        /// Function to pause the windows service.
        /// </summary>
        /// <param name="serviceName">the service name</param>
        /// <param name="nWaitTime">the wait interval</param>
        private static void PauseService(string serviceName, int nWaitTime)
        {
            // Create the service controller instance for the 'serviceName'.
            ServiceController service = new ServiceController(serviceName);
            try
            {
                // Convert the miliseconds 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.
            }
        }

        /// <summary>
        /// Function to start the windows service.
        /// </summary>
        /// <param name="serviceName">the service name</param>
        /// <param name="nWaitTime">the wait interval</param>
        private static void StartService(string serviceName, int nWaitTime)
        {
            // Create the service controller instance for the 'serviceName'.
            ServiceController service = new ServiceController(serviceName);
            try
            {
                // Convert the miliseconds 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 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.
            }
        }

        
        /// <summary>
        /// Function to stop the windows service.
        /// </summary>
        /// <param name="serviceName">the service name</param>
        /// <param name="nWaitTime">the wait interval</param>
        private static void StopService(string serviceName, int nWaitTime)
        {
            // Create the service controller instance for the 'serviceName'.
            ServiceController service = new ServiceController(serviceName);
            try
            {
                // Convert the miliseconds 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 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.
            }
        }

        /// <summary>
        /// Function to restart the windows service.
        /// </summary>
        /// <param name="serviceName">the service name</param>
        /// <param name="nWaitTime">the wait interval</param>
        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 –

Recommended:   Install and Uninstall Windows Service using batch scripts
Share this:

Kiran is a Software engineer by profession and Enthusiastic blogger, love to write articles on computer technology and programming. Reach him at kiran.troubleshootyourself@gmail.com.

We will be happy to hear your thoughts

Leave a reply

Troubleshootyourself
Logo