Barrier Classe
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Consente a più attività di lavorare in modo cooperativo su un algoritmo in parallelo tramite più fasi.
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
- Ereditarietà
-
Barrier
- Attributi
- Implementazioni
Esempio
L'esempio seguente illustra come usare una barriera:
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
Commenti
Un gruppo di attività collabora spostandosi attraverso una serie di fasi, in cui ogni membro del gruppo segnala che è arrivato in una determinata fase e attende implicitamente l'arrivo Barrier di tutti gli altri. Lo stesso Barrier può essere usato per più fasi.
Costruttori
| Nome | Descrizione |
|---|---|
| Barrier(Int32, Action<Barrier>) |
Inizializza una nuova istanza della classe Barrier. |
| Barrier(Int32) |
Inizializza una nuova istanza della classe Barrier. |
Proprietà
| Nome | Descrizione |
|---|---|
| CurrentPhaseNumber |
Ottiene il numero della fase corrente della barriera. |
| ParticipantCount |
Ottiene il numero totale di partecipanti nella barriera. |
| ParticipantsRemaining |
Ottiene il numero di partecipanti nella barriera che non hanno ancora segnalato nella fase corrente. |
Metodi
| Nome | Descrizione |
|---|---|
| AddParticipant() |
Notifica all'oggetto Barrier che ci sarà un partecipante aggiuntivo. |
| AddParticipants(Int32) |
Notifica all'oggetto Barrier che ci saranno partecipanti aggiuntivi. |
| Dispose() |
Rilascia tutte le risorse usate dall'istanza corrente della Barrier classe . |
| Dispose(Boolean) |
Rilascia le risorse non gestite usate da Barriere, facoltativamente, rilascia le risorse gestite. |
| Equals(Object) |
Determina se l'oggetto specificato è uguale all'oggetto corrente. (Ereditato da Object) |
| GetHashCode() |
Funge da funzione hash predefinita. (Ereditato da Object) |
| GetType() |
Ottiene il Type dell'istanza corrente. (Ereditato da Object) |
| MemberwiseClone() |
Crea una copia superficiale del Objectcorrente. (Ereditato da Object) |
| RemoveParticipant() |
Notifica all'oggetto Barrier che ci sarà un partecipante minore. |
| RemoveParticipants(Int32) |
Notifica all'oggetto Barrier che ci saranno meno partecipanti. |
| SignalAndWait() |
Segnala che un partecipante ha raggiunto la barriera e attende che anche tutti gli altri partecipanti raggiungano la barriera. |
| SignalAndWait(CancellationToken) |
Segnala che un partecipante ha raggiunto la barriera e attende che tutti gli altri partecipanti raggiungano la barriera, osservando un token di annullamento. |
| SignalAndWait(Int32, CancellationToken) |
Segnala che un partecipante ha raggiunto la barriera e attende che anche tutti gli altri partecipanti raggiungano la barriera, usando un intero con segno a 32 bit per misurare il timeout, osservando un token di annullamento. |
| SignalAndWait(Int32) |
Segnala che un partecipante ha raggiunto la barriera e attende che anche tutti gli altri partecipanti raggiungano la barriera, usando un intero con segno a 32 bit per misurare il timeout. |
| SignalAndWait(TimeSpan, CancellationToken) |
Segnala che un partecipante ha raggiunto la barriera e attende che anche tutti gli altri partecipanti raggiungano la barriera, usando un TimeSpan oggetto per misurare l'intervallo di tempo, osservando un token di annullamento. |
| SignalAndWait(TimeSpan) |
Segnala che un partecipante ha raggiunto la barriera e attende che anche tutti gli altri partecipanti raggiungano la barriera, usando un TimeSpan oggetto per misurare l'intervallo di tempo. |
| ToString() |
Restituisce una stringa che rappresenta l'oggetto corrente. (Ereditato da Object) |
Si applica a
Thread safety
Tutti i membri pubblici e protetti di Barrier sono thread-safe e possono essere usati simultaneamente da più thread, ad eccezione di Dispose, che deve essere usato solo quando tutte le altre operazioni su Barrier sono state completate.