【发布时间】:2018-05-23 08:51:28
【问题描述】:
当 BlockingCollection 为空时,我从 BlockingCollection 的 TryTake 方法返回 false,尽管预期的行为是阻塞直到集合填满。
请注意,集合不是上限(这应该会影响 TryAdd 而不是 TryTake),并且为添加操作设置的 Timeout 尚未过去。
这是我对 BlockingCollection 对象的包装:
public T TryTake(int timeoutMiliseconds)
{
var result = default(T);
if (!_collection.TryTake(out result, timeoutMiliseconds))
{
throw new InvalidOperationException("Unable to get item from collection.");
}
return result;
}
有什么想法会导致这种情况吗?
我已经根据这篇文章实现了生产者-消费者模式: Multithread processing of the SqlDataReader - Producer/Consumer design pattern
【问题讨论】:
-
异常中包含的 message 说明了什么?
-
我已将其添加到帖子中
-
TryTake不会抛出这个异常,因为收集它是空的,它会因为其他原因抛出它(在这个方法的文档中描述) -
为了他人的利益,上面代码中调用的方法不是
BlockingCollection<T>.TryTake。它是一个自定义类的方法,在内部调用BlockingCollection<T>.TryTake,如果在指定的超时期限内无法获取项目,则抛出指定的异常。按照提供的链接查看该代码。我做了并意识到我的答案不适用。 -
正如@jmcilhinney 提到的,这个异常实际上是在您从链接复制粘贴的
TryTake方法中抛出的。至少阅读您正在复制粘贴的代码,或使用调试器将您指向抛出该异常的代码。
标签: c# task-parallel-library blockingcollection