Build a ParallelWhile looping construct in C#

by Doug Finke on February 27, 2008

in .Net,C#,ParallelFX,Task Parallel Library

Custom parallel looping constructs using the .NET Task Parallel Library.

Methods in the System.Threading.Parallel type are implemented on top of System.Threading.Tasks.Task type, and that they do so taking advantage of Task’s self-replicating functionality

The idea behind replication is that the Task will make just enough copies of itself as is necessary to ensure that all available processing cores are saturated with work.

public static void ParallelWhile(
  Func<bool> condition, Action body)
{
  Task.Create(
    delegate
      { while (condition()) body(); },
    TaskCreationOptions.SelfReplicating
  ).Wait();
}

{ 0 comments… add one now }

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

You are forbidden!