Windows Services are a core part of the Windows Operating System which is responsible for creating and managing the long-running processes. In this article, we will learn how to start, stop, and restart a windows service using C# programming language.

Starting a Windows Service using C#

This method below will start the windows service “aspnet_state” and waits until the service is executing or a timeout halts it.

Before you get started, you will have to add the assembly System.ServiceProcess.dll to your solution, then add the namespace below:

using System.ServiceProcess;

And the method to start windows services:

    public static void StartWindowsService()
    {
        string serviceName = "aspnet_state";
        ServiceController serviceController = new ServiceController(serviceName);
        TimeSpan timeout = TimeSpan.FromMilliseconds(1000);
        serviceController.Start();
        serviceController.WaitForStatus(ServiceControllerStatus.Running, timeout);

    }

Stopping a Windows Service using C#

The following method will stop the Windows Service “aspnet_state” and will wait until the service is stopped or a timeout event occurs.

    public static void StopWindowsService()
    {
        string serviceName = "aspnet_state";
        ServiceController serviceController = new ServiceController(serviceName);
        TimeSpan timeout = TimeSpan.FromMilliseconds(1000);
        serviceController.Stop();
        serviceController.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

    }

Restarting a Windows Service using C#

This method is a combination of the upper two methods. It will stop the service and then start it and waits until the service is running.

    public static void RestartWindowsService()
    {
        string serviceName = "aspnet_state";
        ServiceController serviceController = new ServiceController(serviceName);

        int tickCount1 = Environment.TickCount;
        int tickCount2 = Environment.TickCount;

        TimeSpan timeout = TimeSpan.FromMilliseconds(1000);

        serviceController.Stop();
        serviceController.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
 
        timeout = TimeSpan.FromMilliseconds(1000 - (tickCount1 - tickCount2));

        serviceController.Start();
        serviceController.WaitForStatus(ServiceControllerStatus.Running, timeout);

    }

Related Articles

 

 

 

Last modified: September 21, 2019

Comments

Write a Reply or Comment

Your email address will not be published.