The Barrier Class

The System.Threading namespace in .NET 4.0 introduces a new class named Barrier. The goal of this class is bringing a number of tasks that work concurrently to a common point before taking further steps. Tasks work across multiple phases and they signal they arrived at the barrier, waiting for all other tasks to arrive. The constructor of the class offers several overloads but all have in common the number of tasks participating in the concurrent work. You can also specify the action to take once they arrive at the common point (that is, they reach the barrier and complete the current phase). Notice that the same instance of the Barrier class can be used multiple times, for representing multiple phases. The following code demonstrates how three tasks reach the barrier after their work, signaling the work completion and waiting for other tasks to finish:

image

Basically the code performs these steps:

1. Creates an instance of the Barrier class, adding three participants and specifying the action to take when the barrier is reached.

2. Declares a common job for the three tasks (the myAction object) which simply performs an iteration against running threads simulating some work. When each task completes the work, the Barrier.SignalAndWait method is invoked. This tells the runtime to wait for other tasks to complete their work before going to the next phase.

3. Launches the three concurrent tasks and disposes the myBarrier object at the appropriate time.

The code also reuses the same Barrier instance in order to work across multiple phases. The class also exposes interesting members such as:

AddParticipant and AddParticipants methods which respectively allow adding one or the specified number of participant tasks to the barrier

RemoveParticipant and RemoveParticipants methods which respectively allow removing one or the specified number of participant tasks from the barrier

CurrentPhaseNumber property of type Long, which returns the current phase number

ParticipantCount property of type Integer, which returns the number of tasks involved in the operation

ParticipantsRemaining property of type Integer, which returns the number of tasks that have not invoked the SignalAndWait method yet

A Barrier represents a single phase in the process while multiple instances of the same Barrier class, like in the preceding code, represent multiple phases.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.25.112