ConcurrentBag – Add Multiple Items?

(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<T>(this ConcurrentBag<T> @this, IEnumerable<T> toAdd)
{
    foreach (var element in toAdd)
    {
        @this.Add(element);
    }
}

And then:

ConcurrentBag<int> ccBag = new ConcurrentBag<int>();
var listOfThings = new List<int>() { 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<T>(this ConcurrentBag<T> @this, IEnumerable<T> toAdd)
{
    toAdd.AsParallel().ForAll(t => @this.Add(t));
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)