Usage of Parallel.For

2019-09-08 16:06发布

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

3条回答
Melony?
2楼-- · 2019-09-08 16:11

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.

查看更多
时光不老,我们不散
3楼-- · 2019-09-08 16:12

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.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-09-08 16:17

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(); 
查看更多
登录 后发表回答