Search code examples
c#taskbarrier

Task vs Barrier


So my problem is as follows: I have a list of items to process and I'd like to process the items in parallel then commit the processed items.

The barrier class in C# will allow me to do this - I can run threads in parallel to process the list of items and when SignalAndWait is called and all participants hit he barrier I can commit the processed items.

The Task class will also allow me to do this - on the Task.WaitAll call I can wait for all tasks to complete and I can commit the processed items. If I understand correctly each task will run on it's own thread not a bunch of tasks in parallel on the same thread.

  1. Is my understand correct on both usages for the problem?
  2. Is there any advantage between one over the other?
  3. Is there any way a hybrid solution is better (barrier and tasks?).

Solution

  • Is my understand correct on both usages for the problem?

    I think you have a misunderstanding of the Barrier class. The docs say:

    A barrier is a user-defined synchronization primitive that enables multiple threads (known as participants) to work concurrently on an algorithm in phases.

    A barrier is a synchronization primitive. Comparing it to a unit of work which may be computed in parallel such as a Task isn't correct.

    A barrier can signal all threads to wait until all others have completed some work and check upon that work. By itself, it has no parallel computation capabilities and no threading model behind it.

    Is there any advantage between one over the other?

    As for question 1, you see this is irrelevant.

    Is there any way a hybrid solution is better (barrier and tasks?).

    In your case, I'm not sure its needed at all. If you sinply want to do CPU bound computation in parallel on a collection of items, you have Parallel.ForEach exactly for that purpose. It will partition an enumerable and invoke them in parallel, and block until the entire collection has been computed.