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
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
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).
Just be careful about thread safety in the operation you perform in the delegate.
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.Using PLINQ assuming that ordering is important:
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: