Thursday, March 28, 2013

Run Multiple Tasks in a Windows Service

ServicesBase.Run(ServiceBase[] services) ...that sure made me think you could run multiple implementations of ServiceBase in a single Windows Service; but that is not how it works.

One Service, Multiple Tasks

I often have a very simple use case: I needed to run multiple tasks in a single windows service. For example, one task to poll some email notifications, and one task to listen to HTTP requests that might trigger those same notifications.

I like the basic setup of OnStart, Run, and OnStop, but after authoring several windows services I got tired of writing the same code over and over again. Thus I created the WindowServiceTasks library. Now whenever I need to do another task in a service, I just implement the WindowsServiceTaskBase or WindowsServiceLoopBase class, and my code is all ready to go!

WindowsServiceTasks

Run multiple tasks in a single WindowsService, and let the base library do all of the work setup and tear down for you. The WindowsServiceTasks NuGet package is simple, flexible, and extremely light weight.

Example

public static class Program
{
    public static void Main(params string[] args)
    {
        var logger = new Logger("Demo.log");
        var emailTask = new EmailServiceTask(logger);
        var failTask = new FailServiceTask(logger);
 
        var service = new Service1(logger, emailTask, failTask);
        service.Start(args);
    }
}
public class EmailServiceTask : WindowsServiceLoopBase
{
    private readonly ILogger _logger;
 
    public EmailServiceTask(ILogger logger)
    {
        _logger = logger;
    }
 
    protected override int LoopMilliseconds
    {
        get { return 2000; }
    }
 
    protected override void HandleException(Exception exception)
    {
        _logger.Log(exception);
    }
 
    protected override void RunLoop()
    {
        // TODO Send Email!
        _logger.Log("EmailServiceTask.RunLoop - Sending an email");
    }
 
    public override void OnStart(string[] args)
    {
        _logger.Log("EmailServiceTask.OnStart");
    }
 
    public override void OnStop()
    {
        _logger.Log("EmailServiceTask.OnStop");
    }
 
    protected override void DisposeResources()
    {
    }
}
Shout it

Enjoy,
Tom

Real Time Web Analytics