How to limit BlockingCollection size but keep adding new itens (.NET limited size FIFO)?

微笑、不失礼 提交于 2019-12-21 22:39:43

问题


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


回答1:


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




回答2:


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).



来源:https://stackoverflow.com/questions/17031718/how-to-limit-blockingcollection-size-but-keep-adding-new-itens-net-limited-siz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!