问题
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);
回答1:
locationlist
probably isn't thread-safe.
Therefore, you're corrupting the list.
Instead, you should use .AsParrelel.Select()
to run the delegates in parallel and return an IEnumerable<T>
with the results.
来源:https://stackoverflow.com/questions/15840186/parallel-foreach-race-condition