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(). How
(I know this is an old post, thought I'd add a little something).
Like others have said: yes, you need to add them one by one. In my case, I added a small extension method to make things a bit cleaner, but under the hood it does the same thing:
public static void AddRange(this ConcurrentBag @this, IEnumerable toAdd)
{
foreach (var element in toAdd)
{
@this.Add(element);
}
}
And then:
ConcurrentBag ccBag = new ConcurrentBag();
var listOfThings = new List() { 1, 2, 4, 5, 6, 7, 8, 9 };
ccBag.AddRange(listOfThings);
I also looked at using AsParallel to add within the extension method, but after running some tests on adding a list of strings of various sizes, it was consistantly slower to use AsParallel (as shown here) as opposed to the traditional for loop.
public static void AddRange(this ConcurrentBag @this, IEnumerable toAdd)
{
toAdd.AsParallel().ForAll(t => @this.Add(t));
}