C# Reference ยท Async and Concurrency
Barrier and CountdownEvent
Reference for Barrier and CountdownEvent in C#: phase-based rendezvous, SignalAndWait, post-phase actions, Signal, AddCount, Wait and Reset.
Barrier and CountdownEvent are two small coordination primitives in System.Threading. Both let several threads agree on a moment in time, but they answer different questions.
A Barrier makes a fixed group of participants wait for each other at the end of every phase. Nobody starts phase 2 until everybody has finished phase 1. A CountdownEvent is simpler: it holds a counter, workers call Signal() when they finish, and any thread that calls Wait() is released once the counter reaches zero. Use a barrier for iterative, lock-step algorithms; use a countdown when one thread must wait for N pieces of work to be done.
var barrier = new Barrier(participantCount: 3); barrier.SignalAndWait(); // each participant calls this at the end of a phase var countdown = new CountdownEvent(3); countdown.Signal(); // a worker is done countdown.Wait(); // returns when the count reaches 0
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public class Barrier : IDisposable { public Barrier(int participantCount); public Barrier(int participantCount, Action<Barrier>? postPhaseAction); public void SignalAndWait(); public bool SignalAndWait(int millisecondsTimeout); public bool SignalAndWait(TimeSpan timeout, CancellationToken token); public long AddParticipant(); public void RemoveParticipant(); public int ParticipantCount { get; } public int ParticipantsRemaining { get; } public long CurrentPhaseNumber { get; } } public class CountdownEvent : IDisposable { public CountdownEvent(int initialCount); public bool Signal(); public bool Signal(int signalCount); public void AddCount(); public bool TryAddCount(); public void Reset(); public void Reset(int count); public void Wait(); public bool Wait(TimeSpan timeout); public int CurrentCount { get; } public int InitialCount { get; } public bool IsSet { get; } public WaitHandle WaitHandle { get; } }
| Name | Description |
|---|---|
participantCount |
How many threads (or tasks) take part in each phase. Must be 0 or greater. |
postPhaseAction |
Delegate that runs once at the end of every phase, on one of the participating threads. |
initialCount |
The number of signals a CountdownEvent needs before it becomes set. |
Signal(int) |
Lowers the count by the given amount. Returns true when the count reaches zero. |
SignalAndWait() |
Barrier: announce arrival and block until every participant has arrived. |
Returns: Signal returns true if this call set the event. The timed SignalAndWait overloads return false on timeout.
Errors: Signal throws InvalidOperationException if the count is already zero (or would go below zero). AddCount throws if the count is zero; TryAddCount returns false instead. If the post-phase action throws, every participant sees a BarrierPostPhaseException from SignalAndWait.
Usage notes
- A barrier blocks threads.
SignalAndWaitis a synchronous wait. That is fine for dedicatedThreadobjects. With the thread pool it is risky: if participants outnumber the pool's available threads, the ones that arrived first block forever while the rest never get a thread to run on. - Use real threads or long-running tasks for barriers.
Task.Factory.StartNew(..., TaskCreationOptions.LongRunning)also works. - The post-phase action is the safe place for per-phase work (merging partial results, swapping buffers). It runs while all participants are paused, so it needs no extra locking.
- Participants can change.
AddParticipantandRemoveParticipantlet workers join or leave between phases. A worker that has finished all its phases must callRemoveParticipant, or the others wait for it forever. - A
CountdownEventis single-use unless youReset. Once the count is zero,Signalthrows andAddCountfails. - Fork-join with a countdown: create it with one extra count for the coordinator,
AddCountfor every task you spawn, and signal when each ends. That handles work that spawns more work. - Prefer tasks when you can.
Task.WhenAllwaits for N pieces of work without blocking a thread. Barrier and countdown are for cases where threads must stay alive between phases. - Both types are
IDisposablebecause they own a wait handle; dispose them when finished. - Wait with a timeout (
Wait(TimeSpan),SignalAndWait(int)) in production code, so one stuck worker does not hang the whole program.