ConcurrentBag <T> getting duplicates (doesn't seem to be thread safe)

I have to do something wrong, because I get duplicate items in my parallel bag, here is the chain of events

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




        }


    }

The listing should indicate that if an alread element exists, do not add another identifier, but update some property instead. Now i get the error

System.InvalidOperationException:
    System.Linq.Enumerable.SingleOrDefault [TSource] ( IEnumerable1, Func`2)
    LocalSearch.Processor.CityProcessor.AddListingsToList( , XElement, ConcurrentBag`1) d:\Projects\ListingLocator2\Code\LocalSearch.Processor\Processors.cs: 310
    CallSite.Target(, CallSite, CityProcessor, Object, XElement, ConcurrentBag`1)
    LocalSearch.Processor.CityProcessor.ProcessType( ConcurrentBag`1, GeocodeResults, XElement, ParallelLoopState) d:\Projects\ListingLocator2\Code\LocalSearch.Processor\Processors.cs: 249
    LocalSearch.Processor.CityProcessor. < > c__DisplayClass4.b__0 ( XElement, ParallelLoopState) d:\Projects\ListingLocator2\Code\LocalSearch.Processor\Processors.cs: 137

+3
2

ConcurrentBag , , . , .

: , - X, , , , . : .

, ConcurrentDictionary TryAdd, . lock() , , , List.

+15

, Concurrent Bag , ,

, , previouse .

, , :

THREAD 1        THREAD 2
=-=-=-=-=-=-=-=-=-=-=-=-
Check Exists
                Check Exists
Add New
                Add New

.

+7

All Articles