Search code examples
c#concurrencyconcurrent-collections

ConcurrentBag - Add Multiple Items?


Is there a way to add multiple items to ConcurrentBag all at once, instead of one at a time? I don't see an AddRange() method on ConcurrentBag, but there is a Concat(). However, that's not working for me:

ConcurrentBag<T> objectList = new ConcurrentBag<T>();

timeChunks.ForEach(timeChunk =>
{
    List<T> newList = Foo.SomeMethod<T>(x => x.SomeReadTime > timeChunk.StartTime);
    objectList.Concat<T>(newList);
});

This code used to be in a Parallel.ForEach(), but I changed it to the above so I could troubleshoot it. The variable newList indeed has objects, but after the objectList.Concat<> line, objectList always has 0 objects in it. Does Concat<> not work that way? Do I need to add items to ConcurrentBag one at a time, with the Add() method?


Solution

  • Concat is an extension method provided by LINQ. It is an immutable operation that returns another IEnumerable that can enumerate the source collection followed immediately by the specified collection. It does not, in any way, change the source collection.

    You will need to add your items to the ConcurrentBag one at a time.