Barrier Classe

Definição

Permite que várias tarefas trabalhem de forma colaborativa em um algoritmo em paralelo por meio de várias fases.Enables multiple tasks to cooperatively work on an algorithm in parallel through multiple phases.

public ref class Barrier : IDisposable
public class Barrier : IDisposable
[System.Runtime.InteropServices.ComVisible(false)]
public class Barrier : IDisposable
type Barrier = class
    interface IDisposable
[<System.Runtime.InteropServices.ComVisible(false)>]
type Barrier = class
    interface IDisposable
Public Class Barrier
Implements IDisposable
Herança
Barrier
Atributos
Implementações

Exemplos

O exemplo a seguir mostra como usar uma barreira: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

Comentários

Um grupo de tarefas cooperar percorrendo uma série de fases, onde cada um no grupo sinaliza que ele chegou em Barrier uma determinada fase e espera implicitamente que todos os outros cheguem.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. O mesmo Barrier pode ser usado para várias fases.The same Barrier can be used for multiple phases.

Construtores

Barrier(Int32)

Inicializa uma nova instância da classe Barrier.Initializes a new instance of the Barrier class.

Barrier(Int32, Action<Barrier>)

Inicializa uma nova instância da classe Barrier.Initializes a new instance of the Barrier class.

Propriedades

CurrentPhaseNumber

Obtém o número da fase atual da barreira.Gets the number of the barrier's current phase.

ParticipantCount

Obtém o número total de participantes na barreira.Gets the total number of participants in the barrier.

ParticipantsRemaining

Obtém o número de participantes na barreira que ainda não foram sinalizados na fase atual.Gets the number of participants in the barrier that haven't yet signaled in the current phase.

Métodos

AddParticipant()

Notifica o Barrier de que haverá um participante adicional.Notifies the Barrier that there will be an additional participant.

AddParticipants(Int32)

Notifica o Barrier de que haverá participantes adicionais.Notifies the Barrier that there will be additional participants.

Dispose()

Libera todos os recursos usados pela instância atual da classe Barrier.Releases all resources used by the current instance of the Barrier class.

Dispose(Boolean)

Libera os recursos não gerenciados usados pelo Barrier e opcionalmente libera os recursos gerenciados.Releases the unmanaged resources used by the Barrier, and optionally releases the managed resources.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
RemoveParticipant()

Notifica o Barrier de que haverá um participante a menos.Notifies the Barrier that there will be one less participant.

RemoveParticipants(Int32)

Notifica o Barrier de que haverá menos participantes.Notifies the Barrier that there will be fewer participants.

SignalAndWait()

Indica que um participante atingiu a barreira e aguarda até que todos os outros participantes atinjam a barreira também.Signals that a participant has reached the barrier and waits for all other participants to reach the barrier as well.

SignalAndWait(CancellationToken)

Indica que um participante atingiu a barreira e aguarda até que todos os outros participantes atinjam a barreira, enquanto observa um token de cancelamento.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)

Indica que um participante atingiu a barreira e aguarda até que todos os outros participantes atinjam a barreira também, usando um inteiro com sinal de 32 bits para medir o tempo limite.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)

Indica que um participante atingiu a barreira e aguarda até que todos os outros participantes atinjam a barreira também, usando um inteiro com sinal de 32 bits para medir o tempo limite, enquanto observa um token de cancelamento.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)

Indica que um participante atingiu a barreira e aguarda até que todos os outros participantes atinjam a barreira também, usando um objeto TimeSpan para medir o intervalo de tempo.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)

Indica que um participante atingiu a barreira e aguarda até que todos os outros participantes atinjam a barreira também, usando um objeto TimeSpan para medir o intervalo de tempo, enquanto observa um token de cancelamento.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()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)

Aplica-se a

Acesso thread-safe

Todos os membros públicos e protegidos do Barrier são thread-safe e podem ser usados simultaneamente de vários threads, com exceção de Dispose, que deve ser usado somente quando todas as outras operações no Barrier forem concluídas.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.

Veja também