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