ConcurrentDictionary - 破坏字典或坏代码?

Mad*_*ter 5 c# concurrency multithreading concurrentdictionary

好吧,所以我遇到了一个奇怪的小问题,坦白说我没有想法.我想把它扔出去看看我是否遗漏了一些我做错了,或者ConcurrentDictionary无法正常工作的东西.这是代码:

(Cache是​​一个包含静态ConcurrentDictionary键的类)

var tmp = Cache.Keys.GetOrAdd(type,
                key =>
                {
                    var keys = context.GetKeys(key);
                    if (keys.Count() == 1)
                    {
                        return new KeyInfo
                            {
                                Name = keys.First().Name,
                                Info = key.GetInfo(keys.First().Name)
                            };
                    }

                    return null;
                });

            if (tmp == null)
                Cache.Keys.TryRemove(type, out tmp);

            return tmp;
Run Code Online (Sandbox Code Playgroud)

问题是,偶尔tmpnull导致TryRemove线路运行,但return null;上面的线路永远不会被击中.由于这return null是唯一将null进入词典,它永远不会运行,怎么可能tmp永远是null


包括Cache类(此代码不使用SetNames):

public class Cache
{
    public static ConcurrentDictionary<Type, Info> Keys = new ConcurrentDictionary<Type, Info>();
    public static ConcurrentDictionary<Type, string> SetNames = new ConcurrentDictionary<Type, string>();
}
Run Code Online (Sandbox Code Playgroud)

Mad*_*ter 2

我早就该关闭它的,但我完全忘记了。该示例不是线程安全的,因为TryRemove,但这只是为了调试目的而添加的。我最终通过重写解决了这个问题,所以也许一些关于代码过时的评论是正确的。然而,该代码已不再存在以供确认。

我将此归咎于用户错误(当然是我自己的错误)。感谢大家的时间!