获取字典来自 ConcurrentDictionary在.NET 4.0中
我正在并行化一些后端代码并尝试不破坏接口。我们有几种返回 Dictionary 的方法,在内部,我使用 ConcurrentDictionary 来执行并行操作。
从这些返回字典的最佳方式是什么?
这感觉太简单了:
return myConcurrentDictionary.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
我觉得我错过了一些东西。
I'm parallelizing some back-end code and trying not to break interfaces. We have several methods that return Dictionary and internally, I'm using ConcurrentDictionary to perform Parallel operations on.
What's the best way to return Dictionary from these?
This feels almost too simple:
return myConcurrentDictionary.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
I feel like I'm missing something.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
直接构造
字典
将比调用ToDictionary
稍微更高效。构造函数会将目标字典预先分配到正确的大小,并且不需要在运行过程中动态调整大小。如果您的
ConcurrentDictionary
使用自定义IEqualityComparer
那么您可能需要 将其也传递到构造函数中。Constructing the
Dictionary<K,V>
directly will be slightly more efficient than callingToDictionary
. The constructor will pre-allocate the target dictionary to the correct size and won't need to resize on-the-fly as it goes along.If your
ConcurrentDictionary<K,V>
uses a customIEqualityComparer<K>
then you'll probably want to pass that into the constructor too.没有。这完全没问题。 .NET 序列就是这样。 :D
Nope. This is completely fine. .NET sequences are just nice like that. :D