Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a project in which a stored procedure is Called on a SQL Server 2014.
I fill a DataTable object with the result of the stored procedure.
This is call is done in a base class and after the fill it is running a Parallel.ForEach() on the DataTable. In that virtual proces (each entity overrides the method in base to fill it's entity classes) the data get's set to the entities in a List<Entity>. When the Parallel.ForEach() is finished I call a virtual method which the entity also overrides This marks the end of the dataloading and the LIST<> is set in cache. However I sometimes see that some of Entities in the List<> are NULL. How is that possible? What am I missing to have all the rows set to their proper values?

What I have tried:

I have tried Parallel.ForEach with and without options. One of the options set the simultanious load maximum of 1 record (in fact row based processing).
When I use a regular foreach I do not see this behaviour.
Posted
Updated 21-Aug-17 22:41pm

1 solution

If you look at the List<T> documentation - List<t> Class, MSDN[^]
You will find this at the bottom:
Quote:
It is safe to perform multiple read operations on a List<t>, but issues can occur if the collection is modified while it’s being read. To ensure thread safety, lock the collection during a read or write operation. To enable a collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization. For collections with built-in synchronization, see the classes in the System.Collections.Concurrent namespace. For an inherently thread–safe alternative, see the ImmutableList<t> class.

If you do not implement locking inside the Parallel.ForEach, you will get unpredictable behaviour.
 
Share this answer
 
Comments
Herman<T>.Instance 22-Aug-17 5:53am    
Thanks for the lead Griff! Something to read and workout!
OriginalGriff 22-Aug-17 6:42am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900