问题描述
欲限制BlockingCollection的大小。如果我要添加另一个项目和收集满了,最早的必须拆除。 ?是否有一些具体的这项任务级或我的解决方案是确定
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:这里类似的问题:的
推荐答案
您的解决方案将正常工作,但它不是线程安全的。 BlockingCollection< T>
不提供一种机制来直接处理这个
Your solution will function correctly, but it is not thread safe. BlockingCollection<T>
does not provide a mechanism to handle this directly.
您的解决方案可能仍然块(如果另一个线程调用添加()
后您的 TryTake
)或潜在删除多余的项目(如果当你在另一个线程删除也删除)。
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).
这篇关于如何限制BlockingCollection大小,但不断加入新的itens(.NET规模有限FIFO)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!