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 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();
来源:https://stackoverflow.com/questions/8796506/correct-way-to-guarantee-thread-safety-when-adding-to-a-list-using-parallel-libr