C# 在Parallel.ForEach之外设置断点时,列表计数无效

C# 在Parallel.ForEach之外设置断点时,列表计数无效,c#,.net,multithreading,task-parallel-library,parallel.foreach,C#,.net,Multithreading,Task Parallel Library,Parallel.foreach,我理解,当使用TPL Parallel.ForEach时,我们不需要显式地编写代码“等待”其中的任务完成。但是,我正在将1000个元素从源列表简单地传输到目标列表。在Parallel.ForEach循环外部和之后设置断点时,我看到目标列表中的项目计数无效/不完整。。。为什么? List<int> myList = new List<int> { }; for (int i = 0; i < 1000; i++) { myList.Add(i); } List

我理解,当使用TPL Parallel.ForEach时,我们不需要显式地编写代码“等待”其中的任务完成。但是,我正在将1000个元素从源列表简单地传输到目标列表。在Parallel.ForEach循环外部和之后设置断点时,我看到目标列表中的项目计数无效/不完整。。。为什么?

List<int> myList = new List<int> { };
for (int i = 0; i < 1000; i++) {
    myList.Add(i);
}
List<int> newList = new List<int>();
Parallel.ForEach(myList, x => {
    newList.Add(x);
});
Thread.Sleep(5000);
var test = newList.Count;
List myList=新列表{};
对于(int i=0;i<1000;i++){
添加(i);
}
List newList=新列表();
Parallel.ForEach(myList,x=>{
新增(x);
});
睡眠(5000);
var test=newList.Count;

列表
不是线程安全的,因此不能在并行代码中使用它。您应该使用(或任何其他线程安全集合):

var-bag=新的ConcurrentBag();
Parallel.ForEach(myList,x=>
{
添加(x);
});

您也可以在
newList
周围使用
lock
,但这会使并行化变得无用。

好吧,这种并行化很可能是无用的,即使您使用
ConcurrentBag
来避免锁。
var bag = new ConcurrentBag<int>();
Parallel.ForEach(myList, x =>
{
    bag.Add(x);
});