Barrier Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Permite que várias tarefas funcionem cooperativamente em um algoritmo em paralelo por meio de várias fases.
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:
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 coopera ao passar por uma série de fases, em que cada um no grupo sinaliza que chegou em Barrier determinada fase e aguarda implicitamente a chegada de todas as outras. O mesmo Barrier pode ser usado para várias fases.
Construtores
| Nome | Description |
|---|---|
| Barrier(Int32, Action<Barrier>) |
Inicializa uma nova instância da classe Barrier. |
| Barrier(Int32) |
Inicializa uma nova instância da classe Barrier. |
Propriedades
| Nome | Description |
|---|---|
| CurrentPhaseNumber |
Obtém o número da fase atual da barreira. |
| ParticipantCount |
Obtém o número total de participantes na barreira. |
| ParticipantsRemaining |
Obtém o número de participantes na barreira que ainda não sinalizou na fase atual. |
Métodos
| Nome | Description |
|---|---|
| AddParticipant() |
Notifica que Barrier haverá um participante adicional. |
| AddParticipants(Int32) |
Notifica que Barrier haverá participantes adicionais. |
| Dispose() |
Libera todos os recursos usados pela instância atual da Barrier classe. |
| Dispose(Boolean) |
Libera os recursos não gerenciados usados pelo Barriere, opcionalmente, libera os recursos gerenciados. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetHashCode() |
Serve como a função hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do Objectatual. (Herdado de Object) |
| RemoveParticipant() |
Notifica que Barrier haverá um participante a menos. |
| RemoveParticipants(Int32) |
Notifica que Barrier haverá menos participantes. |
| SignalAndWait() |
Sinaliza que um participante atingiu a barreira e espera que todos os outros participantes alcancem a barreira também. |
| SignalAndWait(CancellationToken) |
Sinaliza que um participante atingiu a barreira e aguarda que todos os outros participantes atinjam a barreira, observando um token de cancelamento. |
| SignalAndWait(Int32, CancellationToken) |
Sinaliza que um participante atingiu a barreira e aguarda que todos os outros participantes alcancem a barreira também, usando um inteiro com sinal de 32 bits para medir o tempo limite, ao observar um token de cancelamento. |
| SignalAndWait(Int32) |
Sinaliza que um participante atingiu a barreira e aguarda que todos os outros participantes alcancem a barreira também, usando um inteiro com sinal de 32 bits para medir o tempo limite. |
| SignalAndWait(TimeSpan, CancellationToken) |
Sinaliza que um participante atingiu a barreira e aguarda que todos os outros participantes alcancem a barreira também, usando um TimeSpan objeto para medir o intervalo de tempo, enquanto observa um token de cancelamento. |
| SignalAndWait(TimeSpan) |
Sinaliza que um participante atingiu a barreira e aguarda que todos os outros participantes alcancem a barreira também, usando um TimeSpan objeto para medir o intervalo de tempo. |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual. (Herdado de Object) |
Aplica-se a
Acesso thread-safe
Todos os membros públicos e protegidos Barrier são thread-safe e podem ser usados simultaneamente de vários threads, com exceção de Dispose, que só deve ser usado quando todas as outras operações no Barrier tiverem sido concluídas.