问题描述
我有一个并行的foreach在完成执行之前关闭连接的问题.当我有一个常规的foreach循环运行时,速度很慢,但是会返回所有内容.一旦我更改为并行foreach,它现在将返回大约95%的数据并终止.
i have an issue with a parallel foreach closing the connection before it finishes executing. when i had a regular foreach loop runnung it was slow but it would return everything. once i changed to a parallel foreach it is now returning about 95% of the data and terminating.
下面是我正在使用的代码:
below is the code that i am using:
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);
推荐答案
locationlist
可能不是线程安全的.因此,您正在破坏列表.
locationlist
probably isn't thread-safe.Therefore, you're corrupting the list.
相反,应该使用.AsParrelel.Select()
并行运行委托,并返回带有结果的IEnumerable<T>
.
Instead, you should use .AsParrelel.Select()
to run the delegates in parallel and return an IEnumerable<T>
with the results.
这篇关于并行Foreach竞赛条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!