我正嘗試使用多線程來更快地處理結果列表。我嘗試使用並行,但每當運行過程方法時,我都沒有收到正確的結果。如何多線程處理方法
private IEnumerable<BulkProcessorResult> GetProccessResults(List<Foo> Foos)
{
var listOfFooLists = CreateListOfFooLists(Foos);
var bulkProcessorResults = new List<BulkProcessorResult>();
Parallel.ForEach(listOfFooLists, FooList =>
{
foreach (var Foo in FooList)
{
var processClaimResult = _processor.Process(Foo);
var bulkProcessorResult = new BulkProcessorResult()
{
ClaimStatusId = (int) processClaimResult.ClaimStatusEnum,
Property1 = Foo.Property1
};
bulkProcessorResults.Add(bulkProcessorResult);
}
});
return bulkProcessorResults;
}
如果我使用正常forEach我得到正確的輸出。如果我使用上面的代碼,當狀態爲1,狀態爲3時,我得到全部2的狀態。'
我對線程真的很陌生,所以任何幫助都會很棒。
什麼是languge?您應該將其添加到標籤。 –
你可能想看看例如作爲中間商店的['ConcurrentQueue'](http://msdn.microsoft.com/zh-cn/library/dd267265.aspx)。 'List '不安全(例如通過調用'Add')來處理多個線程。任何事情都可能發生(也可能會發生)。 –
我看到的第一個問題是,您有多個併發線程將項目添加到'buldProcessResults'。這會導致問題,因爲'List.Add'不能用於多個併發更新。你需要用鎖來保護它,或者使用某種類型的併發數據結構。 –