0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ConcurrentDictionaryの値セット時の注意点

Last updated at Posted at 2018-02-16

個人的に詰まったConcurrentDictionaryの値セット時の注意点を記す。

注意点とは、ConcurrentDictionaryのAddOrUpdateはAddした順序でpairが追加されないことがあるということ。
コードは以下。

    class Program
    {
        static ConcurrentDictionary<string, string> testDictionary = new ConcurrentDictionary<string, string>();

        static public void Main()
        {
            var task = Task.Factory.StartNew(() => { AddDic(); });
            task.Wait();
            return;
        }

        static private void AddDic()
        {
            Dictionary<string, string> strStack = new Dictionary<string, string>(){
            {"Key1", "Value1"},
            {"Key2", "Value2"},
            {"Key3", "Value3"}};

            foreach (KeyValuePair<string, string> pair in strStack)
            {
                Console.WriteLine(pair.Value);
                testDictionary.AddOrUpdate(pair.Key, pair.Value, (Key, Value) => { return Value; });
            }

            foreach(var pair in testDictionary)
            {
                Console.WriteLine(pair.Value);
            }
        }
    }
}

console.png

環境の違い?もあるのかもしれないが、ConcurrentDictionaryではAddした順番は保証されないのかも。
何か勘違いがあればフィードバックいただけると嬉しいです。

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?