How to limit BlockingCollection size but keep addi

2019-04-13 01:17发布

I want to limit the size of the BlockingCollection. If I want to add another item and the collection is full, the oldest must be removed. Is there some Class specific to this task or my solution is ok?

        BlockingCollection<string> collection = new BlockingCollection<string>(10);

        string newString = "";
        //Not an elegant solution?
        if (collection.Count == collection.BoundedCapacity)
        {
            string dummy;
            collection.TryTake(out dummy);
        }
        collection.Add(newString);

EDIT1: Similar question here: ThreadSafe FIFO List with Automatic Size Limit Management

2条回答
干净又极端
2楼-- · 2019-04-13 01:38

Your solution will function correctly, but it is not thread safe. BlockingCollection<T> does not provide a mechanism to handle this directly.

Your solution may still block (if another thread calls Add() after your TryTake) or potentially remove an extra item (if another thread removes while you're also removing).

查看更多
SAY GOODBYE
3楼-- · 2019-04-13 01:48

What you are describing is a LRU cache. There is no implementation that I know of in the standard libraries but would not be hard to create. Look at this c++ implementation for some clues.


Edit

Try this one from code project

查看更多
登录 后发表回答