Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Implement a blocking collection of a concurrent stack

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading