线程下的方法安全吗?我知道ConcurrentDictionary提供了TryRemove方法,但我只是不喜欢拥有一个我永远不会使用的变量值。
ConcurrentDictionary<int, int> myDict = new ConcurrentDictionary<int, int>();
if (myDict.ContainsKey(1))
((IDictionary<int, int>)myDict).Remove(1);
您的目标似乎是通过消除使用out
参数的需求来提高代码的清晰度。这是一个有效的问题,但使用Remove
不是正确的方法。
为自己定义一个辅助方法:
static bool TryRemove<TKey, Value>(
this ConcurrentDictionary<TKey, Value> dict, TKey key) {
TValue value;
return dict.TryRemove(key, out value);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句