0

我有一個並行foreach在完成執行之前關閉連接的問題。當我有一個普通的foreach循環runnung它很慢,但它會返回一切。一旦我改變爲並行foreach,它現在返回大約95%的數據並終止。並行Foreach競爭條件

下面

是我使用的代碼:

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); 

回答

2

locationlist可能不是線程安全的。 因此,你正在破壞列表。

相反,您應該使用.AsParrelel.Select()並行運行代表並返回IEnumerable<T>的結果。