【问题标题】:Is the order of iteration of KeyValuePair<> elements in a Dictionary<int,T>是 Dictionary<int,T> 中 KeyValuePair<> 元素的迭代顺序
【发布时间】:2011-07-25 20:00:15
【问题描述】:

我有一个包含几十万个元素的字典。我需要对字典中的每一对执行冗长的计算,因此为此我想生成一些工作线程并为每个线程分配字典中的一系列元素以进行处理。

我知道哈希表的“顺序未定义”,这很好 - 我关心的是:

如果我从不同的线程执行此操作:

int count = 0;
foreach (KeyValuePair<int, IDataPoint> pair in pointDictionary)
{
    if (count >= min && count <= max) // min,max different for each thread
    {
        // do stuff
    }
    ++count;
}

pointDictionary 中的元素会在不同线程上以相同的顺序被访问吗?

如果没有,我将不得不将字典分解为 N 个字典,并将每个迷你字典中的一个传递给 N 个工作线程。

【问题讨论】:

  • 只是想知道:并行 LINQ 不是一个选项吗? from pair in pointDictionary.AsParallel() select ...?
  • @Michael - 是的,但不幸的是,这段代码的目标是 .net 2.0

标签: c# dictionary iteration


【解决方案1】:

可以,只要字典没有被修改。

Is the order of objects returned by FOREACH stable?

【讨论】:

    猜你喜欢
    • 2011-03-05
    • 2021-02-21
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    相关资源
    最近更新 更多