C# Insert element in a BlockingCollection

Markus Freitag 3,786 Reputation points
2020-12-10T12:42:12.69+00:00

Hello,

    BlockingCollectionPackage = new BlockingCollection<Package>();
switch (type)
                {
                    case 1:
                        //ListPackage.Add(currentPackage);
                        BlockingCollectionPackage.Add(currentPackage);
                        break;
                    case 2:
                        BlockingCollectionPackage.Insert(0, currentPackage);
                        break;
                }

                BlockingCollectionPackage.TryTake(

How can I insert and read an element in a blocking list in index =0?

Thanks for tips!

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,584 questions
0 comments No comments
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,576 Reputation points
    2020-12-11T02:18:40.237+00:00

    This seems impossible. You can think of BlockingCollection as a FIFO queue, you can only add or delete data in order.

    But there is a way to try it, convert it into a list, insert the data into the list, and then create a new BlockingCollection based on the list. It is not elegant, but it may suit your requirements.

                 switch (type)  
                {  
                    case 1:  
                        //ListPackage.Add(currentPackage);  
                        BlockingCollectionPackage.Add(currentPackage);  
                        break;  
                    case 2:  
                        {  
                            List<Package> packages = BlockingCollectionPackage.ToList();  
                            packages.Insert(0, currentPackage);  
                            BlockingCollectionPackage = new BlockingCollection<Package>(new ConcurrentQueue<Package>(packages));  
                            break;  
                        }  
                }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful