The right way to guarantee thread safety when adding to a list using a parallel library

I iterate over the array of connection strings, and in each loop I extract some information and add it to the list. Now I want to use a parallel library to make it multithreaded, but I'm not sure if the library guarantees that writing to the list will be thread safe, or I need to use a lock:

List<SomeType> list = new List<SomeType>(); settings.AsParallel().ForAll(setting => { list.AddRange(GetSomeArrayofSomeType(setting)); /// DO I NEED TO DO LOCKING HERE??? }) 
+4
source share
2 answers

List entry is really unsafe for multi-threaded entries. You need to either use lock to synchronize access, or use a collection of type ConcurrentQueue , which is designed for multi-threaded access.

Lock example (assuming list is local to the method)

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

Or is it better to use SelectMany instead of ForEach

 var list = settings .AsParallel() .SelectMany(setting => GetSomeArrayOfSomeType(setting)) .ToList(); 
+10
source

C # has a new data structure: the Concurrent Collection, and this data type makes the stream safe. See Streaming MSDN Collections

+1
source

Source: https://habr.com/ru/post/1390137/


All Articles