Controlling a Windows Service from .NET Application

You can use the ServiceController component to connect to and control the behavior of existing services. When you create an instance of the ServiceController class, you set its properties so that it interacts with a specific Windows service.

This class is available in namespace
"System.ServiceProcess"
First we need to create object for this class like below
ServiceController oService = new ServiceController("DataImportService");
Here "DataImportService" is the Service Name in my system.

Below are the methods to start,stop,Pause and Continue the services.
oService.Start();
oService.Stop();
oService.Pause();
oService.Continue();


At any time the service is in one of the below state
ContinuePending
Paused
PausePending
Running
StartPending
Start
Stopped
StopPending


We can know the status of the service also using status property
if (service.Status == ServiceControllerStatus.Stopped)
                    service.Start();
above statement checks whether the service is stopped and if yes, it starts the service.

if (service.Status == ServiceControllerStatus.Running)
                    service.Stop();

Some times ASP.net Worker process doesnot have permission to stop or pause the services.For that we can check using CanStop,CanPauseAndContinue,CanShutdown
If(oService.CanStop)
 oService.Stop();

We have another 2 useful overloaded methods
"WaitForStatus(ServiceControllerStatus desiredStatus)" and
"WaitForStatus(ServiceControllerStatus desiredStatus,TimeSpan timeout)" .

First method Infinitely waits for the service to reach the specified status, and 
the second method Waits for the service to reach the specified status or for the specified time-out to expire.

oService.WaitForStatus(ServiceControllerStatus.Stopped) 
It waits until the Service is Stopped.

oService.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMinutes(5));
It waits until the Service is Stopped for fiveminutes. After five minutes it gives an Timeout Exception.


Gopikrishna

    Blogger Comment
    Facebook Comment

1 comments: