ConcurrentBag - Add Multiple Items?

后端 未结 5 1864
庸人自扰
庸人自扰 2021-01-01 08:21

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

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 09:10

    The Concat method is an approach contained at public Enumerable static class that support System.Linq library (inner .NET System.Core assembly).

    BUT, the Concat contains limits to provide the "add range" requirement to ConcurrentBag object, with a behavior as image bellow (at line 47 in Visual Studio):

    To Concat method matches the "add range" requirement, it's necessary to renew the current ConcurrentBag object instance; if the program needs to add multiples ranges, it's necessary to makes auto-reference instances from current ConcurrentBag (recursively) for each range.

    Then, I do not use Concat approach and if I may do a recommendation, I DO NOT RECOMMEND. I follow a similar example from Eric's answer, where I developed a derived class from ConcurrentBag that provides me the AddRange method using the ConcurrentBag base method to add IEnumerable items to the derived instance, as bellow:

    public class ConcurrentBagCompleted : ConcurrentBag
    {
        public ConcurrentBagCompleted() : base() { }
    
        public ConcurrentBagCompleted(IEnumerable collection):base(collection)
        {
        }
    
        public void AddRange(IEnumerable collection)
        {
            Parallel.ForEach(collection, item =>
            {
                base.Add(item);
            });
        }
    }
    

提交回复
热议问题