Parallel Foreach Race Condition

2019-08-16 01:38发布

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条回答
仙女界的扛把子
2楼-- · 2019-08-16 02:04

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.

查看更多
登录 后发表回答