Barrier Barrier Barrier Barrier Class

定義

允許多項工作在多個階段中以平行方式來合作處理某個演算法。Enables multiple tasks to cooperatively work on an algorithm in parallel through multiple phases.

public ref class Barrier : IDisposable
[System.Runtime.InteropServices.ComVisible(false)]
public class Barrier : IDisposable
type Barrier = class
    interface IDisposable
Public Class Barrier
Implements IDisposable
繼承
BarrierBarrierBarrierBarrier
屬性
實作

範例

下列範例示範如何使用障礙:The following example shows how to use a barrier:

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

備註

藉由移動透過一系列的階段,每個群組中表示它已抵達合作的一組工作Barrier在給定的階段,並會隱含等候所有其他項目到達。A group of tasks cooperate by moving through a series of phases, where each in the group signals it has arrived at the Barrier in a given phase and implicitly waits for all others to arrive. 相同Barrier可以用於多個階段。The same Barrier can be used for multiple phases.

建構函式

Barrier(Int32) Barrier(Int32) Barrier(Int32) Barrier(Int32)

初始化 Barrier 類別的新執行個體。Initializes a new instance of the Barrier class.

Barrier(Int32, Action<Barrier>) Barrier(Int32, Action<Barrier>) Barrier(Int32, Action<Barrier>) Barrier(Int32, Action<Barrier>)

初始化 Barrier 類別的新執行個體。Initializes a new instance of the Barrier class.

屬性

CurrentPhaseNumber CurrentPhaseNumber CurrentPhaseNumber CurrentPhaseNumber

取得屏障目前階段的編號。Gets the number of the barrier's current phase.

ParticipantCount ParticipantCount ParticipantCount ParticipantCount

取得在屏障中的參與者總數。Gets the total number of participants in the barrier.

ParticipantsRemaining ParticipantsRemaining ParticipantsRemaining ParticipantsRemaining

取得在目前階段中尚未發出訊號的屏障中參與者數目。Gets the number of participants in the barrier that haven't yet signaled in the current phase.

方法

AddParticipant() AddParticipant() AddParticipant() AddParticipant()

通知 Barrier,表示還會有一個其他參與者。Notifies the Barrier that there will be an additional participant.

AddParticipants(Int32) AddParticipants(Int32) AddParticipants(Int32) AddParticipants(Int32)

通知 Barrier,表示還會有多個其他參與者。Notifies the Barrier that there will be additional participants.

Dispose() Dispose() Dispose() Dispose()

釋放 Barrier 類別目前的執行個體所使用的全部資源。Releases all resources used by the current instance of the Barrier class.

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

釋放 Barrier 所使用的 Unmanaged 資源,並選擇性釋放 Managed 資源。Releases the unmanaged resources used by the Barrier, and optionally releases the managed resources.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
RemoveParticipant() RemoveParticipant() RemoveParticipant() RemoveParticipant()

通知 Barrier,表示會減少一個參與者。Notifies the Barrier that there will be one less participant.

RemoveParticipants(Int32) RemoveParticipants(Int32) RemoveParticipants(Int32) RemoveParticipants(Int32)

通知 Barrier,表示會減少一些參與者。Notifies the Barrier that there will be fewer participants.

SignalAndWait() SignalAndWait() SignalAndWait() SignalAndWait()

發出訊號,表示參與者已到達屏障,並且在等候所有其他參與者到達屏障。Signals that a participant has reached the barrier and waits for all other participants to reach the barrier as well.

SignalAndWait(CancellationToken) SignalAndWait(CancellationToken) SignalAndWait(CancellationToken) SignalAndWait(CancellationToken)

發出訊號,表示參與者已到達屏障,並且在等候所有其他參與者到達,同時觀察取消語彙基元。Signals that a participant has reached the barrier and waits for all other participants to reach the barrier, while observing a cancellation token.

SignalAndWait(Int32) SignalAndWait(Int32) SignalAndWait(Int32) SignalAndWait(Int32)

發出訊號,表示參與者已到達屏障,並且在等候所有其他參與者到達屏障 (使用 32 位元帶正負號的整數以測量逾時)。Signals that a participant has reached the barrier and waits for all other participants to reach the barrier as well, using a 32-bit signed integer to measure the timeout.

SignalAndWait(Int32, CancellationToken) SignalAndWait(Int32, CancellationToken) SignalAndWait(Int32, CancellationToken) SignalAndWait(Int32, CancellationToken)

發出訊號,表示參與者已到達屏障,並且在等候所有其他參與者到達 (使用 32 位元帶正負號的整數以測量逾時),同時觀察取消語彙基元。Signals that a participant has reached the barrier and waits for all other participants to reach the barrier as well, using a 32-bit signed integer to measure the timeout, while observing a cancellation token.

SignalAndWait(TimeSpan) SignalAndWait(TimeSpan) SignalAndWait(TimeSpan) SignalAndWait(TimeSpan)

發出訊號,表示參與者已到達屏障,並且在等候所有其他參與者到達屏障 (使用 TimeSpan 物件以測量時間間隔)。Signals that a participant has reached the barrier and waits for all other participants to reach the barrier as well, using a TimeSpan object to measure the time interval.

SignalAndWait(TimeSpan, CancellationToken) SignalAndWait(TimeSpan, CancellationToken) SignalAndWait(TimeSpan, CancellationToken) SignalAndWait(TimeSpan, CancellationToken)

發出訊號,表示參與者已到達屏障,並且在等候所有其他參與者到達 (使用 TimeSpan 物件以測量時間間隔),同時觀察取消語彙基元。Signals that a participant has reached the barrier and waits for all other participants to reach the barrier as well, using a TimeSpan object to measure the time interval, while observing a cancellation token.

ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)

適用於

執行緒安全性

所有 public 和 protected 成員Barrier是安全執行緒,而且同時從多個執行緒,除了 Dispose,僅能用於時使用上的所有其他作業Barrier已完成。All public and protected members of Barrier are thread-safe and may be used concurrently from multiple threads, with the exception of Dispose, which must only be used when all other operations on the Barrier have completed.

另請參閱