Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to guarantee thread safety when adding to a list using Parallel library

I loop over an array of connection strings and on each loop I extract some information and add to the list. Now, I want to use Parallel library to make it multithreaded, but I'm not sure if the library guarantees that writes to the list would be thread-safe or whether I need to use locking:

List<SomeType> list = new List<SomeType>();

settings.AsParallel().ForAll(setting => 
{
    list.AddRange(GetSomeArrayofSomeType(setting)); /// DO I NEED TO DO LOCKING HERE???
})
like image 838
Andrey Avatar asked Dec 27 '22 08:12

Andrey


1 Answers

Write's to the list are indeed not safe for multithreaded writes. You need to either use a lock to synchronize access or use a collection like ConcurrentQueue which is designed for multithreaded access.

Lock example (assuming list is a local of a method)

List<SomeType> list = new List<SomeType>();
settings.AsParallel().ForAll(setting => { 
  lock (list) {
    list.AddRange(GetSomeArrayofSomeType(setting)); 
  }
});

Or better yet use SelectMany instead of ForEach

var list = settings
  .AsParallel()
  .SelectMany(setting => GetSomeArrayOfSomeType(setting))
  .ToList();
like image 178
JaredPar Avatar answered Jan 30 '23 16:01

JaredPar