Barrier Barrier Barrier Barrier Class

Definición

Habilita varias tareas para que colaboren en un algoritmo en paralelo en varias fases.Enables multiple tasks to cooperatively work on an algorithm in parallel through multiple phases.

public ref class Barrier : IDisposable
[System.Runtime.InteropServices.ComVisible(false)]
public class Barrier : IDisposable
type Barrier = class
    interface IDisposable
Public Class Barrier
Implements IDisposable
Herencia
BarrierBarrierBarrierBarrier
Atributos
Implementaciones

Ejemplos

En el ejemplo siguiente se muestra cómo usar una barrera: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();

    }

}
Imports System.Threading
Imports System.Threading.Tasks
Module BarrierSample

    ' Demonstrates:
    ' Barrier constructor with post-phase action
    ' Barrier.AddParticipants()
    ' Barrier.RemoveParticipant()
    ' Barrier.SignalAndWait(), incl. a BarrierPostPhaseException being thrown
    Sub Main()
        Dim count As Integer = 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
        Dim barrier As New Barrier(3,
                                   Sub(b)
                                       Console.WriteLine("Post-Phase action: count={0}, phase={1}", count, b.CurrentPhaseNumber)
                                       If b.CurrentPhaseNumber = 2 Then
                                           Throw New Exception("D'oh!")
                                       End If
                                   End Sub)

        ' 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
        Dim action As Action =
            Sub()
                Interlocked.Increment(count)
                barrier.SignalAndWait()
                ' during the post-phase action, count should be 4 and phase should be 0

                Interlocked.Increment(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(count)
                Try
                    barrier.SignalAndWait()
                Catch bppe As BarrierPostPhaseException
                    Console.WriteLine("Caught BarrierPostPhaseException: {0}", bppe.Message)
                End Try

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

            End Sub

        ' 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()
    End Sub
End Module

Comentarios

Un grupo de tareas cooperan moviendo a través de una serie de fases, donde cada uno en el grupo señala ha llegado a la Barrier en una fase determinada e implícita espera a que todos los demás a que llegue.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. El mismo Barrier puede usarse para varias fases.The same Barrier can be used for multiple phases.

Constructores

Barrier(Int32) Barrier(Int32) Barrier(Int32) Barrier(Int32)

Inicializa una nueva instancia de la clase Barrier.Initializes a new instance of the Barrier class.

Barrier(Int32, Action<Barrier>) Barrier(Int32, Action<Barrier>) Barrier(Int32, Action<Barrier>) Barrier(Int32, Action<Barrier>)

Inicializa una nueva instancia de la clase Barrier.Initializes a new instance of the Barrier class.

Propiedades

CurrentPhaseNumber CurrentPhaseNumber CurrentPhaseNumber CurrentPhaseNumber

Obtiene el número de la fase actual de la barrera.Gets the number of the barrier's current phase.

ParticipantCount ParticipantCount ParticipantCount ParticipantCount

Obtiene el número total de participantes de la barrera.Gets the total number of participants in the barrier.

ParticipantsRemaining ParticipantsRemaining ParticipantsRemaining ParticipantsRemaining

Obtiene el número de participantes en la barrera que aún no se han señalado en la fase actual.Gets the number of participants in the barrier that haven't yet signaled in the current phase.

Métodos

AddParticipant() AddParticipant() AddParticipant() AddParticipant()

Notifica a Barrier que va a haber un participante adicional.Notifies the Barrier that there will be an additional participant.

AddParticipants(Int32) AddParticipants(Int32) AddParticipants(Int32) AddParticipants(Int32)

Notifica a Barrier que va a haber participantes adicionales.Notifies the Barrier that there will be additional participants.

Dispose() Dispose() Dispose() Dispose()

Libera todos los recursos usados por la instancia actual de la clase Barrier.Releases all resources used by the current instance of the Barrier class.

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Libera los recursos no administrados utilizados por el objeto Barrier y, de forma opcional, libera los recursos administrados.Releases the unmanaged resources used by the Barrier, and optionally releases the managed resources.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
RemoveParticipant() RemoveParticipant() RemoveParticipant() RemoveParticipant()

Notifica a Barrier que va a haber un participante menos.Notifies the Barrier that there will be one less participant.

RemoveParticipants(Int32) RemoveParticipants(Int32) RemoveParticipants(Int32) RemoveParticipants(Int32)

Notifica a Barrier que va a haber menos participantes.Notifies the Barrier that there will be fewer participants.

SignalAndWait() SignalAndWait() SignalAndWait() SignalAndWait()

Señala que un participante ha alcanzado la barrera y espera a que todos los demás participantes alcancen también la barrera.Signals that a participant has reached the barrier and waits for all other participants to reach the barrier as well.

SignalAndWait(CancellationToken) SignalAndWait(CancellationToken) SignalAndWait(CancellationToken) SignalAndWait(CancellationToken)

Señala que un participante ha alcanzado la barrera y espera a que todos los demás participantes alcancen la barrera mientras se observa un token de cancelación.Signals that a participant has reached the barrier and waits for all other participants to reach the barrier, while observing a cancellation token.

SignalAndWait(Int32) SignalAndWait(Int32) SignalAndWait(Int32) SignalAndWait(Int32)

Señala que un participante ha alcanzado la barrera y espera a que todos los demás participantes alcancen también la barrera usando un entero de 32 bits con signo para medir el tiempo de espera.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.

SignalAndWait(Int32, CancellationToken) SignalAndWait(Int32, CancellationToken) SignalAndWait(Int32, CancellationToken) SignalAndWait(Int32, CancellationToken)

Señala que un participante ha alcanzado la barrera y espera a que todos los demás participantes la alcancen también usando un entero de 32 bits con signo para medir el tiempo de espera mientras se observa un token de cancelación.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.

SignalAndWait(TimeSpan) SignalAndWait(TimeSpan) SignalAndWait(TimeSpan) SignalAndWait(TimeSpan)

Señala que un participante ha alcanzado la barrera y espera a que todos los demás participantes alcancen también la barrera usando un objeto TimeSpan para medir el intervalo de tiempo.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.

SignalAndWait(TimeSpan, CancellationToken) SignalAndWait(TimeSpan, CancellationToken) SignalAndWait(TimeSpan, CancellationToken) SignalAndWait(TimeSpan, CancellationToken)

Señala que un participante ha alcanzado la barrera y espera a que todos los demás participantes la alcancen también usando un objeto TimeSpan para medir el intervalo de tiempo, mientras se observa un token de cancelación.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.

ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Se aplica a

Seguridad para subprocesos

Todos los miembros públicos y protegidos de Barrier son seguros para subprocesos y puede usarse simultáneamente desde varios subprocesos, con la excepción de Dispose, que debe ser de solo se usa cuando todas las operaciones en el Barrier ha completado.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.

Consulte también: