Parallel looping and returning 1 collection in C#

An interesting feature in .NET 4.5 is the ability to process collection in parallel. Along with the async/await feature, you can really improve the performance of your application with a few simple steps. Whereas both components are documented really well, I thought this would be a walk in the park. However, you should pay attention when you want to return a collection that was modified in the parallel block. If you don’t, you might be missing a few items in the list. You can easily prevent this from happening if you implement LOCKING, as the following example shows:

The lock check is being done at the time of modifying the opportunities collection. If you don’t lock this, the other threads won’t know if there are any other threads modifying the collection, thereby assuming it has the latest version of the collection with all items from other threads.

Written on February 5, 2015