ConcurrentDictionary操做

  • AddOrUpdate:若是鍵不存在,方法會在容器中添加新的鍵和值,若是存在,則更新現有的鍵和值。
  • GetOrAdd:若是鍵不存在,方法會向容器中添加新的鍵和值,若是存在則返回現有的值,並不添加新值。
  • TryAdd:嘗試在容器中添加新的鍵和值。
  • TryGetValue:嘗試根據指定的鍵得到值。
  • TryRemove:嘗試刪除指定的鍵。
  • TryUpdate:有條件的更新當前鍵所對應的值。
  • GetEnumerator:返回一個可以遍歷整個容器的枚舉器。
 public class Test
    {
        private static ConcurrentDictionary<string, int> testDictionary = new ConcurrentDictionary<string, int>();

        public void test()
        {
            string _key = "a";
            int _value = 0;
            int curValue = 1;

            testDictionary.TryAdd(_key, _value);
            testDictionary.AddOrUpdate(_key, _value, (key, value) => { return value = curValue; });
            testDictionary.TryGetValue(_key, out int getValue);
            testDictionary.GetOrAdd("b", 2);
        }
    }
相關文章
相關標籤/搜索