Skip to content

How to write a Polling Service to check by regular intervals in C#

July 4, 2017

A very simple basic template for writing a How to write a Polling Service to check by regular intervals in C# which I customise slightly further for usage from researching the StackOverflow blog, this is useful for my case checking the database, rather than embedding this process into an existing main Windows service, we can utilise this as a seperate service for smaller tasks to check the SQL database records or particular records, very useful for having a fairly light intensive process.

Here is the generic templated code: –

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace PollingService
public partial class PollingService : ServiceBase
private CancellationTokenSource cts = new CancellationTokenSource();
private Task mainTask = null;

public PollingService()

protected override void OnStart(string[] args)
mainTask = new Task(Poll, cts.Token, TaskCreationOptions.LongRunning);

protected override void OnStop()

private void Poll()
CancellationToken cancellation = cts.Token;
TimeSpan interval = TimeSpan.Zero;
while (!cancellation.WaitHandle.WaitOne(interval))
// Poll here
// Ocassionally check the cancellation state.
if (cancellation.IsCancellationRequested)
interval = TimeSpan.FromMinutes((Convert.ToDouble(ConfigurationSettings.AppSettings[“WaitAfterSuccessInterval”])));
catch (Exception)
// Log the exception
//string fromTimeString = result.ToString(“hh’:’mm”);
//interval = Convert.ToDouble(ConfigurationSettings.AppSettings[“WaitAfterSuccessInterval”]);
//interval = TimeSpan.FromMinutes((ConfigurationSettings.AppSettings[“WaitAfterSuccessInterval”]));
interval = TimeSpan.FromMinutes((Convert.ToDouble(ConfigurationSettings.AppSettings[“WaitAfterSuccessInterval”])));
//TimeSpan result = TimeSpan.FromMinutes(interval);

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: