Barrier in .NET 4.0

By | August 18, 2011


A Barrier defines a phases in such a way that the Thread executing some set of code reaches a certain point where it is stopped and sent to wait until all the Threads running in Barrier gets the Signal. The set of code that it executes is called Pre-Phaze work until each of them reaches a Barrier. Once all the Thread reaches the Barrier, it executes the Post-Phaze code.

Thus Barrier class is used to very specific case, in which you require to specify a barrier for the Threads to stop and wait for other Threads to finish the execution and finally run a method specified as callback to the Barrier as Post – Phaze code.

Lets look the same in code :

public static Barrier barrier = new Barrier(5, e =>
    Console.WriteLine("All threads Finishes");
static void Main(string[] args)
    Thread t1 = new Thread(() => ProcessPhaze1());
    Thread t2 = new Thread(() => ProcessPhaze1());
    Thread t3 = new Thread(() => ProcessPhaze1());
    Thread t4 = new Thread(() => ProcessPhaze1());
    Thread t5 = new Thread(() => ProcessPhaze1());



public static void ProcessPhaze1()


Here each thread calls ProcessPhaze1 from main. Thus the ProcessPhaze1 will be called in parallel by 5 threads. Once each of them finishes execution (for simplicity I have just used Thread.Sleep) it signals the Barrier to wait and thus it stops itself. As shown here, you can specify the Timeout value for the SignalAndWait to ensure that deadlock does not occur.

Once all Threads are signalled, it calls the callback specified as argument in Barrier. The first argument 5 specifies how many threads are participant of the Barrier. Here I am using 5 Threads. If I change the argument to 2, it will print the Phaze2 callback twice.

This is because the argument specifies after how many signals are received, it should call this callback. After each callback is executed, the Barrier PhazeNumber gets incremented. You can get the value of Phaze number from barrier.CurrentPhaseNumber.

Barrier also supports dynamic addition and removal of participants too.

I hope this post helps you.

Thanks for reading.