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???
})
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 likeConcurrentQueue
which is designed for multithreaded access.Lock example (assuming
list
is a local of a method)Or better yet use
SelectMany
instead ofForEach