这种方法线程安全吗

is this approach thread safe

线程下面的方法安全吗?我知道 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);
}