从字典中读取数据时,为什么锁 [英] Why lock when reading from a dictionary

查看:123
本文介绍了从字典中读取数据时,为什么锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一本书我读,C#3果壳中列出了代码混淆,穿线。
在在应用服务器线程安全的话题,下面的代码是作为一个UserCache的例子:

I am confused by a code listing in a book i am reading, C# 3 in a Nutshell, on threading. In the topic on Thread Safety in Application Servers, below code is given as an example of a UserCache:

static class UserCache
{
    static Dictionary< int,User> _users = new Dictionary< int, User>();

    internal static User GetUser(int id)
    {
        User u = null;

        lock (_users) // Why lock this???
            if (_users.TryGetValue(id, out u))
                return u;

        u = RetrieveUser(id); //Method to retrieve from databse

        lock (_users) _users[id] = u; //Why lock this???
            return u;
    }
}



作者解释了为什么RetrieveUser方法不在锁定,这是为了避免锁定缓存一段较长的时间。结果
我很困惑,为什么锁定TryGetValue和字典的,因为即使在字典上述被两次,如果2个线程更新更新用相同的ID未检索同时调用。

The authors explain why the RetrieveUser method is not in a lock, this is to avoid locking the cache for a longer period.
I am confused as to why lock the TryGetValue and the update of the dictionary since even with the above the dictionary is being updated twice if 2 threads call simultaneously with the same unretrieved id.

什么是被锁定的字典预先阅读所有的意见和见解实现吗?结果
非常感谢。

What is being achieved by locking the dictionary read?
Many thanks in advance for all your comments and insights.

推荐答案

词典< TKEY的,TValue> 类的is不是线程安全

如果一个线程写入一个关键字典,而不同的线程读取的字典,它可能会搞砸。 (例如,如果在写操作触发阵列调整,或者如果这两个键是散列冲突)

If one thread writes one key to the dictionary while a different thread reads the dictionary, it may get messed up. (For example, if the write operation triggers an array resize, or if the two keys are a hash collision)

因此,该代码使用一个锁,以防止并发写入。

Therefore, the code uses a lock to prevent concurrent writes.

这篇关于从字典中读取数据时,为什么锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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