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);
        }
    }

猜你喜欢

转载自www.cnblogs.com/cg-931210/p/9263414.html