Barrier Classe
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Permet à plusieurs tâches de travailler de manière coopérative sur un algorithme en parallèle via plusieurs 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
- Héritage
-
Barrier
- Attributs
- Implémente
Exemples
L’exemple suivant montre comment utiliser une barrière :
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
Remarques
Un groupe de tâches collabore en passant par une série de phases, où chacun dans le groupe signale qu’il est arrivé à une Barrier phase donnée et attend implicitement que tous les autres arrivent. La même Barrier chose peut être utilisée pour plusieurs phases.
Constructeurs
| Nom | Description |
|---|---|
| Barrier(Int32, Action<Barrier>) |
Initialise une nouvelle instance de la classe Barrier. |
| Barrier(Int32) |
Initialise une nouvelle instance de la classe Barrier. |
Propriétés
| Nom | Description |
|---|---|
| CurrentPhaseNumber |
Obtient le nombre de la phase actuelle de la barrière. |
| ParticipantCount |
Obtient le nombre total de participants dans la barrière. |
| ParticipantsRemaining |
Obtient le nombre de participants dans la barrière qui n’ont pas encore signalé dans la phase actuelle. |
Méthodes
| Nom | Description |
|---|---|
| AddParticipant() |
Avertit qu’il Barrier y aura un participant supplémentaire. |
| AddParticipants(Int32) |
Avertit le fait qu’il Barrier y aura des participants supplémentaires. |
| Dispose() |
Libère toutes les ressources utilisées par l’instance actuelle de la Barrier classe. |
| Dispose(Boolean) |
Libère les ressources non managées utilisées par le Barrier, et libère éventuellement les ressources managées. |
| Equals(Object) |
Détermine si l’objet spécifié est égal à l’objet actuel. (Hérité de Object) |
| GetHashCode() |
Sert de fonction de hachage par défaut. (Hérité de Object) |
| GetType() |
Obtient la Type de l’instance actuelle. (Hérité de Object) |
| MemberwiseClone() |
Crée une copie superficielle du Objectactuel. (Hérité de Object) |
| RemoveParticipant() |
Avertit qu’il Barrier y aura un participant moins. |
| RemoveParticipants(Int32) |
Avertit qu’il Barrier y aura moins de participants. |
| SignalAndWait() |
Signale qu’un participant a atteint la barrière et attend que tous les autres participants atteignent également la barrière. |
| SignalAndWait(CancellationToken) |
Signale qu’un participant a atteint la barrière et attend que tous les autres participants atteignent la barrière, tout en observant un jeton d’annulation. |
| SignalAndWait(Int32, CancellationToken) |
Signale qu’un participant a atteint la barrière et attend que tous les autres participants atteignent également la barrière, en utilisant un entier signé 32 bits pour mesurer le délai d’expiration, tout en observant un jeton d’annulation. |
| SignalAndWait(Int32) |
Signale qu’un participant a atteint la barrière et attend que tous les autres participants atteignent également la barrière, en utilisant un entier signé 32 bits pour mesurer le délai d’expiration. |
| SignalAndWait(TimeSpan, CancellationToken) |
Signale qu’un participant a atteint la barrière et attend que tous les autres participants atteignent également la barrière, en utilisant un TimeSpan objet pour mesurer l’intervalle de temps, tout en observant un jeton d’annulation. |
| SignalAndWait(TimeSpan) |
Signale qu’un participant a atteint la barrière et attend que tous les autres participants atteignent également la barrière, en utilisant un TimeSpan objet pour mesurer l’intervalle de temps. |
| ToString() |
Retourne une chaîne qui représente l’objet actuel. (Hérité de Object) |
S’applique à
Cohérence de thread
Tous les membres publics et protégés d’entre Barrier eux sont thread-safe et peuvent être utilisés simultanément à partir de plusieurs threads, à l’exception de Dispose, qui ne doit être utilisé que lorsque toutes les autres opérations sur le site Barrier sont terminées.