Parallel Foreach Race Condition

六眼飞鱼酱① 提交于 2019-12-12 03:48:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!