从字典中读取可能存在或不存在的值的线程安全方法 [英] Thread safe way of reading a value from a dictionary that may or may not exist

查看:81
本文介绍了从字典中读取可能存在或不存在的值的线程安全方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我被ConcurrentDictionary宠坏了,它是很棒的TryGetValue方法.但是,我只能使用常规的Dictionary,因为这是在针对手机和其他平台的可移植类库中.我正在尝试编写一个非常有限的Dictionary子集,并以线程安全的方式公开它.

So, I've been spoiled by ConcurrentDictionary and it's awesome TryGetValue method. However, I'm constrained to using only regular Dictionary because this is in a portable class library targeting phone and other platforms. I'm trying to write a very limited subset of a Dictionary and exposing it in a thread-safe manner.

我基本上需要ConcurrentDictionary中的 GetOrAdd 之类的东西.现在,我已经像这样实现了:

I basically need something like GetOrAdd from ConcurrentDictionary. Right now, I have this implemented like:

        lock (lockdictionary)
        {
            if (!dictionary.ContainsKey(name))
            {
                value = new foo();
                dictionary[name] = value;
            }
            value = dictionary[name];
        }

这基本上可以得到吗?我认为,如果键不存在并添加了锁,则仅需要真正,但是,没有很好的如果存在则获取值,否则返回null"方法.如果我不包含ContainsKey位,那么当键不存在时,我会得到一个异常,因为键不存在.

Is this basically as good as I can get it? I think locking is only really required if the key doesn't exist and it gets added, however, there is no good "get value if it exists, return null otherwise" method. If I were to leave out the ContainsKey bit, when the key didn't exist I'd get an exception because the key doesn't exist.

无论如何,我可以将其升级为更精简的版本吗?还是这只是常规词典所能做的最好的事情?

Is there anyway I could get this to a more lean version? Or is this just the best a regular dictionary can do?

推荐答案

即使在并发编写者在场的情况下,即使阅读也需要锁定.所以,是的,这和变异字典一样好.

Locking is required even for reading in the presence of concurrent writers. So yes, this is as good as it gets if you mutate the dictionary.

当然,每次写东西时,您总是可以为整个词典创建一个副本.这样,读者可能会看到过时的版本,但他们可以放心地阅读.

You can of course always create a copy of the entire dictionary each time something is written. That way readers might see an out-of-date version but they can safely read.

这篇关于从字典中读取可能存在或不存在的值的线程安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆