Welcome to weblogs.com.pk Sign in | Join | Help

.NET 4: CountdownEvent

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 (var countdown = new CountdownEvent(1))
{
    foreach (var devicePoller in devicePollers)
    {
        countdown.AddCount();
        ThreadPool.QueueUserWorkItem(delegate
        {
            devicePoller.PollAndProcessData();
            countdown.Signal();
        });
    }

    countdown.Signal();
    countdown.Wait();
}
//All the work is done
Published Friday, October 23, 2009 12:33 PM by khurram
Filed under:

Comments

No Comments

New Comments to this post are disabled