正确的方法使用并行库添加到列表时保证线程安全 [英] Correct way to guarantee thread safety when adding to a list using Parallel library
问题描述
在连接字符串数组,并在每次循环我提取一些信息,并添加到列表中我循环。现在,我想用并行库,使其多线程的,但我不知道如果库保证写入名单将是线程安全的或我是否需要使用锁定:
列表<&SOMETYPE GT;名单=新名单,LT; SOMETYPE>();
settings.AsParallel()的ForAll(设置=方式>
{
list.AddRange(GetSomeArrayofSomeType(设置)); ///我需要做的LOCKING在这里? ??
})
写的对名单确实不适合多线程写入安全。您需要为使用锁定
来同步访问或使用像 ConcurrentQueue
集合这是专为多线程访问。
锁例如(假设列表
是本地的方法)
列表<&SOMETYPE GT;名单=新名单,LT; SOMETYPE>();
settings.AsParallel()的ForAll(设置=方式> {
锁(名单){
list.AddRange(GetSomeArrayofSomeType(设置));
}
} );
或者更好的使用的SelectMany
而不是的ForEach
VAR列表=设置
.AsParallel()
.SelectMany(设置=> GetSomeArrayOfSomeType(设置))
.ToList();
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();
这篇关于正确的方法使用并行库添加到列表时保证线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!