gpt4 book ai didi

c# - BlockingCollection TryTake() 何时可以返回 false?

转载 作者:太空狗 更新时间:2023-10-29 22:09:17 26 4
gpt4 key购买 nike

假设 BlockingCollection 在下面使用 ConcurrentQueue,TryTake(T, Int32) method 什么时候可以如果您使用 Timeout.Infinite,则返回 false?

最佳答案

这是一个简单的例子,说明它何时可以返回 false:当集合被标记为 CompleteAdding 并变为空时

//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!");
}

这允许您禁止在队列中添加新项目并完成剩余元素的处理

关于c# - BlockingCollection<T> TryTake() 何时可以返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21195224/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com