BlockingCollection< T> TryTake()返回假? [英] When can BlockingCollection<T> TryTake() return false?
本文介绍了BlockingCollection< T> TryTake()返回假?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设BlockingCollection在下面使用ConcurrentQueue,何时 TryTake(T,Int32)方法如果使用的是Timeout.Infinite,则返回false。
Assuming the BlockingCollection is using a ConcurrentQueue underneath, when could the TryTake(T, Int32) method return false if you are using Timeout.Infinite?
推荐答案
这是一个简单的示例,它显示何时可以返回false:当集合被标记为 CompleteAdding
并成为空容器时
Here's a simple example that shows when it can return false: when the collection is marked as CompleteAdding
and becomes emptу
//by default, BlockingCollection will use ConcurrentQueue
BlockingCollection<int> coll = new BlockingCollection<int>();
coll.Add(1);
coll.Add(2);
coll.CompleteAdding();
int item;
if (coll.TryTake(out item, -1))
{
Console.WriteLine(item);
}
if (coll.TryTake(out item, -1))
{
Console.WriteLine(item);
}
if (coll.TryTake(out item, -1))
{
//this won't get hit
}
else
{
Console.WriteLine("TryTake returned false!");
}
这可让您禁止在队列中添加新项目并禁止剩余元素的完整处理
This allows you to forbid adding new items in queue and complete processing of remaining elements
这篇关于BlockingCollection< T> TryTake()返回假?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文