什么情况下 ConcurrentBag.TryTake() 会失败?
我正在考虑在我正在编写的程序中使用 ConcurrentBag ,但是我似乎无法在 TryTake 上找到足够的文档。
我知道该方法可能会失败,但我找不到可能发生此类失败的情况的解释,以及失败后集合将处于什么状态。
如果只是在另一个线程已经删除了该项目的情况下,那么我不在乎,但我真正负担不起的是我想要删除的项目在调用后仍在集合中。
情况会如此吗?
I'm thinking of using a ConcurrentBag in a program I'm writing, however I can't seem to find enough documentation on TryTake.
I understand that the method might fail, but I can't find an explanation of the cases in which such failure might happen, and what state the collection will be left in after the failure.
If it's only in the case of another thread having already removed the item then I don't care, but what I can't really afford is the item I want to remove to still be in the collection after the call.
Can this ever be the case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据文档,如果没有可用的物品(即袋子是空的),则返回 false。由于它是一个线程安全的集合,因此不应该存在“空”和多个线程的问题。
您必须考虑
结果 T
的文档以及返回值
:http://msdn.microsoft.com/en-us/library/dd287255。 ASPX
From the documentation it returns false if no item is available to take i.e. the bag is empty. As it is a thread-safe collection there should be no issues around 'empty' and multiple threads.
You have to take the documentation for
result T
as well as thereturn value
into consideration:http://msdn.microsoft.com/en-us/library/dd287255.aspx
鉴于您正在处理多线程,在
TryTake
决定返回 false(并设置它是default(T)
的返回值),以及对TryTake
的调用实际返回到您的代码的时刻。因此,当您能够处理错误结果时,袋子中可能确实有一件物品。
Given that you're dealing with multithreading, there's nothing to stop another thread from adding an item to the bag between the moment at which
TryTake
has decide to return false (and set it's return value todefault(T)
), and the moment at which the call toTryTake
actually returns to your code.So by the time you're able to handle the false result, there may actually be an item in the bag.