.NET 4 - Barrier Class

Published on Friday, October 23, 2009

Barrier class is newly introduced in .NET 4 and it enables the multiple tasks to cooperatively work on an algorithm in parallel through multiple phases. For instance you are polling the data from multiple data source; and this polling is multi step process. While polling in parallel you want coordination that on each step the parallel running tasks before moving to next step coordinate with each other. Visual Studio 2010 and .NET Framework 4 Training Kit (October Preview) has a great sample which I am reproducing below!

using System.Threading;

class HelloWorld
{
    static Barrier sync;
    static CancellationToken token;
    
    static void Main(string [] args)
    {
        var source = new CancellationTokenSource();
        token = source.Token;
        sync = new Barrier(3);

        var charlie = new Thread(() => DriveToBoston("Charlie", TimeSpan.FromSeconds(1)));
        charlie.Start();
        
        var mac = new Thread(() => DriveToBoston("Mac", TimeSpan.FromSeconds(2)));
        mac.Start();
        
        var dennis = new Thread(() => DriveToBoston("Dennis", TimeSpan.FromSeconds(3)));
        dennis.Start();
        
        charlie.Join();
        mac.Join();
        dennis.Join();
        
        Console.ReadKey();
    }
    
    static void DriveToBoston(string name, TimeSpan timeToGasStation)
    {
        try
        {
            Console .WriteLine("[{0}] Leaving House", name);
            // Perform some work
            Thread.Sleep(timeToGasStation);
            Console.WriteLine("[{0}] Arrived at Gas Station", name);
            // Need to sync here
            sync.SignalAndWait(token);
            // Perform some more work
            Console.WriteLine("[{0}] Leaving for Boston", name);
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("[{0}] Caravan was cancelled! Going home!", name);
        }
    }
}