Export (0) Print
Expand All

Barrier Class

Enables multiple tasks to cooperatively work on an algorithm in parallel through multiple phases.

System.Object
  System.Threading.Barrier

Namespace:  System.Threading
Assembly:  System (in System.dll)

[ComVisibleAttribute(false)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public class Barrier : IDisposable

The Barrier type exposes the following members.

  NameDescription
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsBarrier(Int32)Initializes a new instance of the Barrier class.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsBarrier(Int32, Action<Barrier>)Initializes a new instance of the Barrier class.
Top

  NameDescription
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsCurrentPhaseNumberGets the number of the barrier's current phase.
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsParticipantCountGets the total number of participants in the barrier.
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsParticipantsRemainingGets the number of participants in the barrier that haven’t yet signaled in the current phase.
Top

  NameDescription
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsAddParticipantNotifies the Barrier that there will be an additional participant.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsAddParticipantsNotifies the Barrier that there will be additional participants.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsDispose()Releases all resources used by the current instance of the Barrier class.
Protected methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsDispose(Boolean)Releases the unmanaged resources used by the Barrier, and optionally releases the managed resources.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsRemoveParticipantNotifies the Barrier that there will be one less participant.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsRemoveParticipantsNotifies the Barrier that there will be fewer participants.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsSignalAndWait()Signals that a participant has reached the barrier and waits for all other participants to reach the barrier as well.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsSignalAndWait(CancellationToken)Signals that a participant has reached the barrier and waits for all other participants to reach the barrier, while observing a cancellation token.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsSignalAndWait(Int32)Signals that a participant has reached the barrier and waits for all other participants to reach the barrier as well, using a 32-bit signed integer to measure the timeout.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsSignalAndWait(TimeSpan)Signals that a participant has reached the barrier and waits for all other participants to reach the barrier as well, using a TimeSpan object to measure the time interval.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsSignalAndWait(Int32, CancellationToken)Signals that a participant has reached the barrier and waits for all other participants to reach the barrier as well, using a 32-bit signed integer to measure the timeout, while observing a cancellation token.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsSignalAndWait(TimeSpan, CancellationToken)Signals that a participant has reached the barrier and waits for all other participants to reach the barrier as well, using a TimeSpan object to measure the time interval, while observing a cancellation token.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsToStringReturns a string that represents the current object. (Inherited from Object.)
Top

A group of tasks cooperate by moving through a series of phases, where each in the group signals it has arrived at the Barrier in a given phase and implicitly waits for all others to arrive. The same Barrier can be used for multiple phases.

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

The following example shows how to use a barrier:

using System;
using System.Threading;
using System.Threading.Tasks;

class BarrierDemo
{
    // Demonstrates: 
    //      Barrier constructor with post-phase action 
    //      Barrier.AddParticipants() 
    //      Barrier.RemoveParticipant() 
    //      Barrier.SignalAndWait(), incl. a BarrierPostPhaseException being thrown 
    static void BarrierSample()
    {
        int count = 0;

        // Create a barrier with three participants 
        // Provide a post-phase action that will print out certain information 
        // And the third time through, it will throw an exception
        Barrier barrier = new Barrier(3, (b) =>
        {
            Console.WriteLine("Post-Phase action: count={0}, phase={1}", count, b.CurrentPhaseNumber);
            if (b.CurrentPhaseNumber == 2) throw new Exception("D'oh!");
        });

        // Nope -- changed my mind.  Let's make it five participants.
        barrier.AddParticipants(2);

        // Nope -- let's settle on four participants.
        barrier.RemoveParticipant();


        // This is the logic run by all participants
        Action action = () =>
        {
            Interlocked.Increment(ref count);
            barrier.SignalAndWait(); // during the post-phase action, count should be 4 and phase should be 0
            Interlocked.Increment(ref count);
            barrier.SignalAndWait(); // during the post-phase action, count should be 8 and phase should be 1 

            // The third time, SignalAndWait() will throw an exception and all participants will see it
            Interlocked.Increment(ref count);
            try
            {
                barrier.SignalAndWait();
            }
            catch (BarrierPostPhaseException bppe)
            {
                Console.WriteLine("Caught BarrierPostPhaseException: {0}", bppe.Message);
            }

            // The fourth time should be hunky-dory
            Interlocked.Increment(ref count);
            barrier.SignalAndWait(); // during the post-phase action, count should be 16 and phase should be 3
        };

        // Now launch 4 parallel actions to serve as 4 participants
        Parallel.Invoke(action, action, action, action);

        // This (5 participants) would cause an exception: 
        // Parallel.Invoke(action, action, action, action, action); 
        //      "System.InvalidOperationException: The number of threads using the barrier 
        //      exceeded the total number of registered participants." 

        // It's good form to Dispose() a barrier when you're done with it.
        barrier.Dispose();

    }

}

.NET Framework

Supported in: 4.5, 4

.NET Framework Client Profile

Supported in: 4

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

All public and protected members of Barrier are thread-safe and may be used concurrently from multiple threads, with the exception of Dispose, which must only be used when all other operations on the Barrier have completed.

Show:
© 2014 Microsoft