0

I have query with AsParallel().ForAll is sometimes skipping some records and sometimes returning null records in my case.

I am not sure for this is the exact reason for this. Is the mechanism for parellal for in .Net reliable?

Edit: Sample code

var collection=.. Collection from database
var processedCollection=...
collection.Where(h => h.Id == id).AsParallel().ForAll(h =>
{
    var processedCollectionItem = ....logic to process the item
    processedCollectionItem.Where(c=>c.....).AsParallel().ForAll(c =>
    {
        //logic to process the records
    });
    processedCollection.Add(processedCollectionItem);
});
Naresh Goradara
  • 1,896
  • 2
  • 30
  • 41
  • 7
    I strongly suspect that it's your *usage* of it that's at fault, not the BCL. Can you post a short but complete program demonstrating the problem? – Jon Skeet Apr 06 '15 at 11:26

2 Answers2

2

I guess processedCollection is a collection that is not thread safe (probably a simple generic list?).

A simple solution is to use a lock:

lock (processedCollection) // or better use a dedicated lock object
{
    processedCollection.Add(processedCollectionItem);
}

or use a thread safe collection like a ConcurrentBag<>.

sloth
  • 99,095
  • 21
  • 171
  • 219
2

Instead of adding stuff to a collection in a parallel loop, it would probably be better to let the framework handle building the collection.

Example:

var processedCollection = collection
    .Where(h => h.Id == id)
    .AsParallel()
    .Select(h => ProcessItem(h))
    .ToArray();

In ProcessItem the processing would occur. Doing that in parallel seems unnecessary.

Allrameest
  • 4,364
  • 2
  • 34
  • 50