0

我有一个并行 foreach 在完成执行之前关闭连接的问题。当我有一个常规的 foreach 循环运行时,它很慢,但它会返回所有内容。一旦我更改为并行 foreach,它现在返回大约 95% 的数据并终止。

下面是我正在使用的代码:

var USPostalCodes = repository.GetUSPostalCodes();
                var CAPostalCodes = repository.GetCAPostalCodes();

                Parallel.ForEach(spreadsheetinfo, location =>
                {

                    LocationData Locationdata = new LocationData()
                    {
                        id = location.Id,
                        Market = repository.GetMarketsForPostalCode(location.PostalCode, uploadedFile, USPostalCodes, CAPostalCodes),
                    };

                    locationlist.Add(Locationdata);
                });

I added the following code to check and see what was going on, and that fixed it so that it is returning all rows so i know that a race condition exists but what i can't figure out is why and how ot fix it.  any suggestions would be greatly appreciated

Console.WriteLine("Processing {0} on thread {1}", Locationdata,
                                    Thread.CurrentThread.ManagedThreadId);
4

1 回答 1

2

locationlist可能不是线程安全的。因此,您正在破坏列表。

相反,您应该使用.AsParrelel.Select()并行运行委托并返回IEnumerable<T>结果。

于 2013-04-05T17:45:41.183 回答