Sunday, June 5, 2011

Introduction to Windows Services in .NET

Create new project and select windows service (Visual C# / Windows / Windows Service). Enter the project name, e.g. „MyService“.
View designer of the Service1.cs and click to Add Installer in the Properties window.
It adds a ProjectInstaller­.cs file to the project. This file contains two components, a ServiceInsta­ller and a ServiceProces­sInstaller.

Click to serviceInstaller1 and in the Properties window set ServiceName to „MyService“, change DisplayName (shown in Microsoft Management Console) and fill in the Description field. You can also set StartType to automatic or manual service starting.


Click to serviceProces­sInstaller1 and change the Account property to a value you need. It's an account under which the system runs the service. Account descriptions can be found in ServiceAccount enumeration.

Complete the implementation of OnStart and OnStop methods in the service class.


Start a Service

The following method tries to start a service specified by a service name. Then it waits until the service is running or a timeout occurs.

public static void StartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
// ...
}
}
Stop service

The following method tries to stop the specified service and it waits until the service is stopped or a timeout occurs.

public static void StopService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
}
catch
{
// ...
}
}

Restart service
This method combinates both previous methods. It tries to stop the service (and waits until it's stopped) then it begins to start the service (and waits until the service is running). The specified timeout is used for both operations together.

[C#]
public static void RestartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
int millisec1 = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

// count the rest of the timeout
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));

service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
// ...
}
}