Delashmate
Delashmate

Reputation: 2424

Usage of Parallel.For

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

Upvotes: 0

Views: 461

Answers (3)

cdiggins
cdiggins

Reputation: 18243

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(); 

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273804

and combine every value output after the loop finished

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.

Upvotes: 1

Allon Guralnek
Allon Guralnek

Reputation: 16141

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.

Upvotes: 1

Related Questions