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

我的梦境 提交于 2019-12-05 17:26:42

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