【发布时间】:2011-03-27 06:20:27
【问题描述】:
我对正在阅读的书中的代码清单感到困惑,C# 3 in a Nutshell, on threading。 在应用程序服务器中的线程安全主题中,以下代码作为 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 调用,字典也会更新两次。
通过锁定字典读取可以实现什么?
非常感谢您的所有 cmets 和见解。
【问题讨论】:
标签: c# multithreading caching dictionary locking