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

旧街凉风 提交于 2019-12-07 08:21:45

问题


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???
})

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!