Home > Enterprise >  Implement a blocking collection of a concurrent stack
Implement a blocking collection of a concurrent stack

Time:03-16

I have a class to hold a stack of strings to paint to a UI with which I want to block if there are no items, and take LIFO if there are a lot of items.

internal class PaintStack
{
    private BlockingCollection<PaintString> paintStack;

    public PaintStack()
    {
        paintStack = new BlockingCollection<PaintString>(new ConcurrentStack<PaintString>());
    }

    public void Add(PaintString p)
    {
        paintStack.Add(p);
    }

    public PaintString Take()
    {
        return paintStack.Take();
    }
}

When I add a new object to the collection I am seeing all objects as the same as the new object. What's going on?

New strings come in with price value of 1450.4

new price

Now the whole concurrent stack has a price of 1450.4

stack

Then next string comes in with price value of 1460.4

new price

The whole stack appears to have a value of 1460.4

stack

What is going wrong?

CodePudding user response:

You are probably adding multiple references to the same object to the list. So when you change your object, everything in the list is affected, since they are all referring to the same object.

To solve this I would suggest using an immutable object or record. So instead of changing an existing object, you would create a new object with your requested changes. This neatly avoids issues like this, and helps ensuring thread-safety.

Also, as mentioned in the comment, a stack is Last In First Out (LIFO). If you want FIFO, use a ConcurrentQueue.

Also, you do not need concurrent* if you are not writing multithreaded code. My standard recommendation regarding multithreaded code is to only do it if you are familiar with the risks, and how to mitigate them. Multi threading is infamous for causing serious, hard to reproduce, bugs.

  •  Tags:  
  • c#
  • Related