.NET 4 - CountdownEvent

Published on Friday, October 23, 2009

A while ago I was asked to complete a job that polls a data from many devices connected over satellite (slow and congested) links. The requirement was to poll data periodically; and somtimes while previous poll cycle was running the next poll time gets triggered. I used the Abortable Threadpool to implement this but still had to implement my own Count Down approach so that I can track if the job gets completed in the alloted time; it simply returns else after the allowed time; it aborts all the remaining queued work! It was really ugly implementation; I had to periodically check if the completed count has reached the queued work count. Now we have a new class in .NET; CountdownEvent; which exactly does the same. Its a synchronization primitive that signals when its count is reached zero. The code now looks neat!

using System.Collections.Generic;
using System.Threading;

class DevicePoller
{
    public void PollAndProcessData() { }
}

class HelloWorld
{
    void Example(IEnumerable<DevicePoller> devicePollers)
    {
        using (var countdown = new CountdownEvent(1))
        {
            foreach (var devicePoller in devicePollers)
            {
                countdown.AddCount();
                ThreadPool.QueueUserWorkItem(delegate
                {
                    devicePoller.PollAndProcessData();
                    countdown.Signal();
                });
            }
            countdown.Signal();
            countdown.Wait();
        }
    }
}