C# ConcurrentDictionary.TryAdd 会失败吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11501931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can ConcurrentDictionary.TryAdd fail?
提问by Dave Lawrence
This is more of an academic question... but can ConcurrentDictionary.TryAddfail? And if so in what cases and why?
这更像是一个学术问题……但是ConcurrentDictionary.TryAdd会失败吗?如果是这样,在什么情况下以及为什么?
采纳答案by oleksii
Yes it can, here are the conditions (from msdn):
是的,可以,以下是条件(来自 msdn):
- ArgumentNullException- when the key is null reference
- OverflowException- when max number of elements was reached
- It returns falseif an element with the same key already exist
- ArgumentNullException- 当键为空引用时
- OverflowException- 当达到最大元素数时
- 如果已存在具有相同键的元素,则返回false
Just to reiterate, this is nothing to do with concurrency. If you worry about two threads inserting an item at the same time then the following can happen:
重申一下,这与并发无关。如果您担心两个线程同时插入一个项目,则可能会发生以下情况:
- Both inserts work fine, if the keys are different.
- One insert works fine and returns true, the other insert fails (with no exception) and returns false. This happens if two threads try to insert an item with the same key and basically only one would win and the other would lose.
- 如果键不同,两个插入都可以正常工作。
- 一个插入工作正常并返回 true,另一个插入失败(无一例外)并返回 false。如果两个线程尝试插入具有相同键的项目并且基本上只有一个会赢而另一个会输,则会发生这种情况。
回答by Chris Gessler
Sure it can. If the key already exists, the method will return false.
当然可以。如果键已经存在,该方法将返回 false。
Ref: http://msdn.microsoft.com/en-us/library/dd267291.aspx
参考:http: //msdn.microsoft.com/en-us/library/dd267291.aspx
Return Value Type: System.Boolean true if the key/value pair was added to the ConcurrentDictionary successfully. If the key already exists, this method returns false.
返回值类型:System.Boolean 如果键/值对已成功添加到 ConcurrentDictionary,则为 true。如果键已存在,则此方法返回 false。
回答by Guffa
It will fail when the key already exists in the dictionary.
当键已存在于字典中时,它将失败。
If the value can't be added because you run out memory, you will get an exception instead.
如果由于内存不足而无法添加该值,则会出现异常。

