84652

Usage of Parallel.For

Question:

How can I make the code below parallel, without locks

List l = new List(); foreach (var item in sourceCollection) { L.Add(Process(item)); }

I prefer answers for c# 3.5, but 4.0 will be also ok

Answer1:

Here's an example of taking a sequence of numbers, performing some costly operation on each of them in parallel, and then aggregating the result (not in parallel).

int[] numbers = { 1, 1, 2, 3, 5, 8, 13 }; int[] squaredNumbers = new int[numbers.Length]; Parallel.For(0, numbers.Length, i => squaredNumbers[i] = (int)Math.Pow(numbers[i], 2)); int sum = squaredNumbers.Sum();

Just be careful about thread safety in the operation you perform in the delegate.

Answer2:

<blockquote>

and combine every value output after the loop finished

</blockquote>

If we take that literally there is no problem, just store those values in a(nother) array and process/combine them after the loop.

But I suspect you want to combine (add) them during the loop. And then without locking.

The best solution would seem not to use a Parallel.For() but a LINQ .AsParallel() solution.

Answer3:

Using PLINQ assuming that ordering is important:

var result = sourceCollection .AsParalle() .AsOrdered() .Select(item => Process(item);

I highly doubt that you need the results as a list, but if you did you could always convert the result to a list via:

var L = result.ToList();

Recommend

  • PySpark: create dict of dicts from dataframe?
  • Create a List of from a base class
  • How does Task Parallel Library scale on a terminal server or in a web application?
  • WCF Proxy Pooling - Is it worth it?
  • Akka pattern for handling asynchronous actions in receive
  • MySQL - get sum() grouped max() of group
  • Hadoop shuffle uses which protocol?
  • How can I sum two different columns at once where one contains Decimal objects in pandas?
  • Using Delphi + Jedi, losing USB data when device sends it “too fast”
  • Group By and Sum clauses in LINQ
  • Column 'dbo.User.FB_UserId' is invalid in the select list because it is not contained in e
  • cudaFree is not freeing memory
  • Cannot use a lambda expression as an argument to a dynamically dispatched operation
  • Aggregate all dataframe row pair combinations using pandas
  • How to calculate total across columns but one?
  • Laravel lmutator $this->attributes return 'Undefined index: id'
  • Simplify where clause with repeated associated type restrictions
  • FTS3 searches in ORMLite?
  • How to concat Pandas dataframe columns
  • SQL - Select lowest values with group by and order by?
  • R convert summary result (statistics with all dataframe columns) into dataframe
  • TFS 2015 - Waiting for an agent to be requested
  • How to synchronize jQuery dialog box to act like alert() of Javascript
  • Approximate Order-Preserving Huffman Code
  • Authentication in Play! and RestEasy
  • Object and struct member access and address offset calculation
  • Grails calculated field in SQL
  • AES padding and writing the ciphertext to a disk file
  • Is possible to count alias result on mysql
  • php design question - will a Helper help here?
  • retrieve vertices with no linked edge in arangodb
  • AngularJs get employee from factory
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Change div Background jquery
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Authorize attributes not working in MVC 4
  • apache spark aggregate function using min value
  • Sorting a 2D array using the second column C++
  • java string with new operator and a literal