Barrier Klasa

Definicja

Umożliwia współdziałanie wielu zadań nad algorytmem równolegle przez wiele faz.

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
Dziedziczenie
Barrier
Atrybuty
Implementuje

Przykłady

W poniższym przykładzie pokazano, jak używać bariery:

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

Uwagi

Grupa zadań współpracuje poprzez przejście przez serię faz, gdzie każda w grupie sygnalizuje, że dotarła do Barrier danej fazy i niejawnie czeka na przybycie wszystkich innych. Tego samego Barrier można używać w wielu fazach.

Konstruktory

Barrier(Int32)

Inicjuje nowe wystąpienie klasy Barrier.

Barrier(Int32, Action<Barrier>)

Inicjuje nowe wystąpienie klasy Barrier.

Właściwości

CurrentPhaseNumber

Pobiera liczbę bieżącej fazy bariery.

ParticipantCount

Pobiera łączną liczbę uczestników bariery.

ParticipantsRemaining

Pobiera liczbę uczestników bariery, która nie została jeszcze zasygnalizowana w bieżącej fazie.

Metody

AddParticipant()

Powiadamia o tym Barrier , że zostanie dodatkowy uczestnik.

AddParticipants(Int32)

Powiadamia o tym Barrier , że będą dodatkowymi uczestnikami.

Dispose()

Zwalnia wszystkie zasoby używane przez bieżące wystąpienie klasy Barrier.

Dispose(Boolean)

Zwalnia niezarządzane zasoby używane przez Barrierprogram i opcjonalnie zwalnia zarządzane zasoby.

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetType()

Type Pobiera wartość bieżącego wystąpienia.

(Odziedziczone po Object)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
RemoveParticipant()

Powiadamia o tym Barrier , że będzie jeden mniej uczestnik.

RemoveParticipants(Int32)

Powiadamia o tym Barrier , że będzie mniej uczestników.

SignalAndWait()

Sygnały, że uczestnik osiągnął barierę i czeka, aż wszyscy inni uczestnicy również dotrą do bariery.

SignalAndWait(CancellationToken)

Sygnały, że uczestnik osiągnął barierę i czeka, aż wszyscy inni uczestnicy dotrą do bariery, obserwując token anulowania.

SignalAndWait(Int32)

Sygnały, że uczestnik osiągnął barierę i czeka, aż wszyscy inni uczestnicy dotrą do bariery, używając 32-bitowej liczby całkowitej ze znakiem, aby zmierzyć limit czasu.

SignalAndWait(Int32, CancellationToken)

Sygnały, że uczestnik osiągnął barierę i czeka, aż wszyscy inni uczestnicy dotrą do bariery, używając 32-bitowej liczby całkowitej ze znakiem, aby zmierzyć limit czasu, obserwując token anulowania.

SignalAndWait(TimeSpan)

Sygnały, że uczestnik osiągnął barierę i czeka, aż wszyscy inni uczestnicy dotrą do bariery, używając TimeSpan obiektu do mierzenia przedziału czasu.

SignalAndWait(TimeSpan, CancellationToken)

Sygnały, że uczestnik osiągnął barierę i czeka, aż wszyscy inni uczestnicy osiągną barierę, używając TimeSpan obiektu do mierzenia przedziału czasu, obserwując token anulowania.

ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Dotyczy

Bezpieczeństwo wątkowe

Wszystkie publiczne i chronione elementy członkowskie są Barrier bezpieczne wątkowo i mogą być używane współbieżnie z wielu wątków, z wyjątkiem Dispose, które muszą być używane tylko wtedy, gdy wszystkie inne operacje na Barrier obiekcie zostały ukończone.

Zobacz też