Barrier Třída

Definice

Umožňuje více úkolům spolupracovat na algoritmu paralelně prostřednictvím více fází.

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
Dědičnost
Barrier
Atributy
Implementuje

Příklady

Následující příklad ukazuje, jak použít bariéru:

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

Poznámky

Skupina úkolů spolupracuje tím, že prochází řadu fází, kde každá ze skupin signalizuje, že přišla v Barrier dané fázi a implicitně čeká na přijetí všech ostatních. Totéž Barrier lze použít pro více fází.

Konstruktory

Barrier(Int32)

Inicializuje novou instanci Barrier třídy.

Barrier(Int32, Action<Barrier>)

Inicializuje novou instanci Barrier třídy.

Vlastnosti

CurrentPhaseNumber

Získá počet aktuální fáze bariéry.

ParticipantCount

Získá celkový počet účastníků v bariérě.

ParticipantsRemaining

Získá počet účastníků v bariérě, které ještě nebyly signalizovaly v aktuální fázi.

Metody

AddParticipant()

Upozorní na Barrier to, že bude k dispozici další účastník.

AddParticipants(Int32)

Upozorní na Barrier to, že budou další účastníci.

Dispose()

Uvolní všechny prostředky používané aktuální instancí Barrier třídy.

Dispose(Boolean)

Uvolní nespravované prostředky používané nástrojem Barriera volitelně uvolní spravované prostředky.

Equals(Object)

Určí, zda se zadaný objekt rovná aktuálnímu objektu.

(Zděděno od Object)
GetHashCode()

Slouží jako výchozí funkce hash.

(Zděděno od Object)
GetType()

Type Získá aktuální instanci.

(Zděděno od Object)
MemberwiseClone()

Vytvoří použádnou kopii aktuálního souboru Object.

(Zděděno od Object)
RemoveParticipant()

Upozorní na Barrier to, že jeden účastník bude mít méně účastníků.

RemoveParticipants(Int32)

Upozorní na to Barrier , že bude k dispozici méně účastníků.

SignalAndWait()

Signály, že účastník dosáhl bariéry a čeká na dosažení bariéry i všichni ostatní účastníci.

SignalAndWait(CancellationToken)

Signály, že účastník dosáhl bariéry a čeká, až se všichni ostatní účastníci dostanou k bariérě, zatímco pozorují token zrušení.

SignalAndWait(Int32)

Signály, že účastník dosáhl bariéry a čeká na dosažení bariéry i všichni ostatní účastníci, pomocí 32bitového celého čísla podepsaného k měření časového limitu.

SignalAndWait(Int32, CancellationToken)

Signály, že účastník dosáhl bariéry a čeká, až se všichni ostatní účastníci dostanou do bariéry, a to pomocí 32bitového celého čísla podepsaného k měření časového limitu při sledování tokenu zrušení.

SignalAndWait(TimeSpan)

Signály, že účastník dosáhl bariéry a čeká na dosažení bariéry i všichni ostatní účastníci, pomocí objektu TimeSpan k měření časového intervalu.

SignalAndWait(TimeSpan, CancellationToken)

Signály, že účastník dosáhl bariéry a čeká na dosažení bariéry i všichni ostatní účastníci, a to pomocí TimeSpan objektu k měření časového intervalu při sledování tokenu zrušení.

ToString()

Vrátí řetězec, který představuje aktuální objekt.

(Zděděno od Object)

Platí pro

Bezpečný přístup z více vláken

Všechny veřejné a chráněné členy Barrier jsou bezpečné pro přístup z více vláken a mohou být použity souběžně z více vláken, s výjimkou Dispose, které se musí použít pouze v případě, že byly dokončeny všechny ostatní operace Barrier .

Viz také