Windows Service with Cancelable Task

Page content

Background

Recently, we had requirement wherein a process should,

  • Periodically (Poll) or Asynchronously (Pub-sub) listen on incoming requests/messages. The whole process is expected to be long running.
  • Should also implement clean disposal of in-flight requests and subsequent cleanup using something similar to Cancelble Context in Go

The first of the objective is somewhat dependent on mechanism (Pub/sub, Listener), protocol (TCP, HTTP etc.). For the second one, .NET framework (and .NET Core) offers CancellationToken. It is maint for co-operative cancellation between threads and Task Objects. So Armed with this, is it possible to come up with a template that allows cancellation of long running task while also being deployed as Windows Service (or using systemd in Linux) ?

Lets get Started,

Approach

We can use below to construct service,

  • Topshelf - Allows Hosting services in-process as console apps or Windows services.
  • NLog - For Logging

Accordingly, we will have below Components,

  • Listener.cs - It wraps the long running process in a C# Task. It exposes Start and Stop functions which are essentially event handlers awaiting for Signal from the service.

Refer Gist here

  • Program.cs - It configures the startup parameters for the service and initializes it. Using Topshelf, one can easily debug it as Console Application before deploying it as Service.

Refer Gist here

Above Code was targetted at .NET Framework but the same can potentially be used on .NET Core thus targetting both Windows and Linux.

Happy Coding !!