本帖最后由 yanx8844 于 2010-05-19 11:32:12 编辑

解决方案 »

  1.   

    up谁来接分。自己测试了一下,遍历没有问题。
    我的测试代码:
     ConcurrentDictionary<int, int> cities = new ConcurrentDictionary<int, int>();            Parallel.Invoke(
                    () =>
                    {
                        int i = 0;
                        while (true)
                        {
                            int j = i + 10;
                            for (; i < j; i++)
                            {
                                if (cities.TryAdd(i, i))
                                    Console.WriteLine("++Add {0}", i);
                                Thread.Sleep(10);
                            }
                            i -= 5;
                            j = i + 5;
                            for (; i < j; i++)
                            {
                                int t;
                                if (cities.TryRemove(i, out t))
                                    Console.WriteLine("--Remove {0}", i);
                                Thread.Sleep(10);
                            }
                        }
                    },
                    () =>
                    {
                        while (true)
                        {
                            Console.WriteLine("***********************************************************");
                            foreach (var item in cities)
                            {
                                Console.WriteLine("<<Output {0}", item.Value);
                                Thread.Sleep(5);
                            }
                            Thread.Sleep(1000);
                        }
                    });
      

  2.   

    关于ConcurrentDictionary 的迭代如果以下面的形式进行迭代,迭代的时候不会阻塞线程,但是会读到脏数据           foreach (var item in MyDictionary)
                {
                    //其他代码
                }如果下面这种形式,迭代的结果将是MyDictionary某一时刻的快照,不包含脏数据           foreach (var item in MyDictionary.ToArray())
                {
                    //其他代码
                }同时,ConcurrentDictionary 的Count, Keys, Values 属性也是某一时刻的快照