这是使用Parallel.ForEach的()是线程安全的? [英] Is this use of Parallel.ForEach() thread safe?
问题描述
从本质上讲,我与这方面的工作:
Essentially, I am working with this:
var data = input.AsParallel();
List<String> output = new List<String>();
Parallel.ForEach<String>(data, line => {
String outputLine = "";
// ** Do something with "line" and store result in "outputLine" **
// Additionally, there are some this.Invoke statements for updating UI
output.Add(outputLine);
});
输入一个列表与LT;弦乐&GT;
对象。在的ForEach()
语句进行一些处理上的每个值,更新UI,并将结果添加到输出
列表
。有什么内在的错误呢?
Input is a List<String>
object. The ForEach()
statement does some processing on each value, updates the UI, and adds the result to the output
List
. Is there anything inherently wrong with this?
注:
- 输出顺序的不重要
- Output order is unimportant
更新:
根据反馈,我已经得到了,我添加了一个手动锁定
到 output.Add
语句,以及到UI更新code
Based on feedback I've gotten, I've added a manual lock
to the output.Add
statement, as well as to the UI updating code.
推荐答案
是的; 列表&LT; T&GT;
不是线程安全的,所以增加了它特设免遭任意线程(很可能在同一时间)是注定的。你应该使用一个线程安全的列表,而不是,或添加手动锁定。或者,也许有一个 Parallel.ToList
。
Yes; List<T>
is not thread safe, so adding to it ad-hoc from arbitrary threads (quite possibly at the same time) is doomed. You should use a thread-safe list instead, or add locking manually. Or maybe there is a Parallel.ToList
.
另外,如果它的问题:插入顺序将得不到保证。
Also, if it matters: insertion order will not be guaranteed.
该版本的是的安全,虽然:
This version is safe, though:
var output = new string[data.Count];
Parallel.ForEach<String>(data, (line,state,index) =>
{
String outputLine = index.ToString();
// ** Do something with "line" and store result in "outputLine" **
// Additionally, there are some this.Invoke statements for updating UI
output[index] = outputLine;
});
在这里我们使用首页
更新每个并行调用不同的数组索引。
here we are using index
to update a different array index per parallel call.
这篇关于这是使用Parallel.ForEach的()是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!