我一定在某个地方做错了什么,因为我的concurrentbag中出现了重复的项,以下是事件的发生过程:
var listings = new ConcurrentBag<JSonListing>();
Parallel.ForEach(Types, ParallelOptions, (type, state) =>
{
...
status = ProcessType(listings, status, type, state);
....
});
private GeocodeResults ProcessType(ConcurrentBag<JSonListing> listings, GeocodeResults status, XElement type, ParallelLoopState state)
{
....
AddListingsToList(results, type, listings);
....
}
private void AddListingsToList(dynamic results, XElement type, ConcurrentBag<JSonListing> listings)
{
var typeMustMatch = type.Attribute("TypeMustMatch").Value;
var typeID = Convert.ToInt32(type.Attribute("ID").Value);
foreach (var result in results.results)
{
var foundListing = listings.SingleOrDefault(x => x.ID == result.id);
if (foundListing != null)
{
var typeIDs = foundListing.TypeIDs.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
if (!typeIDs.Contains(typeID.ToString()))
{
foundListing.TypeIDs += "|" + typeID;
}
}
else
{
var listing = new JSonListing { ID = result.id, ReferenceNumber = result.reference, TypeIDs = typeID.ToString(), TypeMustMatch = typeMustMatch };
listings.Add(listing);
}
}
}
添加列表应该保证,如果元素已经存在,则不会添加另一个具有相同ID的元素,而是更新某些属性。现在我得到的错误是:
System.InvalidOperationException:序列包含多个匹配的元素
在System.Linq.Enumerable.SingleOrDefault [TSource](IEnumerable`1 source,Func`2 predicate)中
在LocalSearch.Processor.CityProcessor.AddListingsToList(Object results,XElement type,ConcurrentBag`1 listings)中,位于d:\ Projects \ ListingLocator2 \ Code \ LocalSearch.Processor \ Processors.cs: line 310
在CallSite.Target(Closure,CallSite,CityProcessor,Object,XElement,ConcurrentBag`1)中
在LocalSearch.Processor.CityProcessor.ProcessType(ConcurrentBag`1 listings,GeocodeResults status,XElement type,ParallelLoopState state)中,位于d:\ Projects \ ListingLocator2 \ Code \ LocalSearch.Processor \ Processors.cs: line 249
在LocalSearch.Processor.CityProcessor。&lt;&gt; c__DisplayClass4.b__0(XElement type,ParallelLoopState state)中,位于d:\ Projects \ ListingLocator2 \ Code \ LocalSearch.Processor \ Processors.cs: line 137
ProcessType
会有一些重大的副作用,但这在示例中被省略了。 - Jon