none
Parallel.ForEach (C#)

    Question

  • I need little help to convert below foreach code into the parallel.Foreach code. Below code is in C#

     

    List<string> result = new List<string>();
    foreach (var path in environment.Paths)
    {
     result.AddRange(GetSearchResult(path));
    } 
     return result;

     


    Saturday, May 07, 2011 10:58 AM

Answers

  • First of all, you'll need a concurrent collection (or to lock the list, but I'd strongly recommend the concurrent collections.  Then you can use the parallel ForEach to build the results and then convert to list once done:

    			var results = new ConcurrentQueue<string>();
    
    			Parallel.ForEach(environment.Paths, p =>
    			  {
    			    foreach (var r in GetSearchResult(p))
    			    {
    			      results.Enqueue(r);
    			    }
    			  });
    
    			return results.ToList();
    
    


    James Michael Hare

    Blog: http://www.geekswithblogs.net/BlackRabbitCoder

    Twitter: @BlkRabbitCoder

    There are 10 kinds of people in the world: those who know binary and those who don't...

    Monday, May 09, 2011 2:24 PM
  • I would personally switch this around to use a one-line PLINQ query instead:

    return environment.Paths.AsParallel().SelectMany(path => GetSearchResult(path)).ToList();
    
    


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Monday, May 09, 2011 4:36 PM

All replies

  • First of all, you'll need a concurrent collection (or to lock the list, but I'd strongly recommend the concurrent collections.  Then you can use the parallel ForEach to build the results and then convert to list once done:

    			var results = new ConcurrentQueue<string>();
    
    			Parallel.ForEach(environment.Paths, p =>
    			  {
    			    foreach (var r in GetSearchResult(p))
    			    {
    			      results.Enqueue(r);
    			    }
    			  });
    
    			return results.ToList();
    
    


    James Michael Hare

    Blog: http://www.geekswithblogs.net/BlackRabbitCoder

    Twitter: @BlkRabbitCoder

    There are 10 kinds of people in the world: those who know binary and those who don't...

    Monday, May 09, 2011 2:24 PM
  • I would personally switch this around to use a one-line PLINQ query instead:

    return environment.Paths.AsParallel().SelectMany(path => GetSearchResult(path)).ToList();
    
    


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Monday, May 09, 2011 4:36 PM