什么情况下 ConcurrentBag.TryTake() 会失败?

发布于 2024-10-10 07:33:42 字数 375 浏览 0 评论 0原文

我正在考虑在我正在编写的程序中使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绾颜 2024-10-17 07:33:42

根据文档,如果没有可用的物品(即袋子是空的),则返回 false。由于它是一个线程安全的集合,因此不应该存在“空”和多个线程的问题。

您必须考虑结果 T 的文档以及返回值

result T:当该方法返回时,result 包含从 ConcurrentBag 中删除的对象,如果包为空,则结果包含 T 的默认值。

返回:如果成功删除对象,则返回true;否则为假。

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 the return value into consideration:

result T: When this method returns, result contains the object removed from the ConcurrentBag or the default value of T if the bag is empty.

Return: true if an object was removed successfully; otherwise, false.

http://msdn.microsoft.com/en-us/library/dd287255.aspx

零度° 2024-10-17 07:33:42

鉴于您正在处理多线程,在 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 to default(T)), and the moment at which the call to TryTake 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文