参数锁定 [英] Parametric locking

查看:76
本文介绍了参数锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以用参数锁定吗?让我举一个例子:

 // 从数据库或缓存中加载用户
公共用户LoadUser( int  id)
{
    // 获取缓存密钥
    字符串 cacheKey = "  + id .ToString();

    // 尝试从缓存中加载用户
    用户用户= MemoryCache.Default.Get(cacheKey) as 用户;
    如果(用户!= )
        返回用户;

    // 现在使用cacheKey锁定

    // 从数据库中读取用户
    用户= LoadUserFromDatabase(id);

    // 将用户保存到缓存
    MemoryCache.Default.Set(cacheKey,user,< some cache time>);

    返回用户;
} 



问题在于,在并发线程和相同ID的情况下,用户将被加载两次.但是没有理由锁定具有不同ID的用户的加载,这是绝大多数情况.

那么,是否可以使用参数进行锁定?

预先感谢.

解决方案

双重检查锁定 [<一个href ="http://en.wikipedia.org/wiki/Double_checked_locking_pattern" target ="_ blank" title ="New Window"> ^ ],确实可以满足我的要求.

Hi, is it possible to lock with parameters? Let me give you an example:

// Load user from database or cache
public User LoadUser(int id)
{
    // Get cache key
    string cacheKey = "User" + id.ToString();

    // Try to load user from cache
    User user = MemoryCache.Default.Get(cacheKey) as User;
    if (user != null)
        return user;

    // Now lock with cacheKey

    // Read user from database
    user = LoadUserFromDatabase(id);

    // Save user to cache
    MemoryCache.Default.Set(cacheKey, user, <some cache time>);

    return user;
}



The problem is that with concurrent threads and the same id, the user will get loaded twice. But there''s no reason to lock loading of users with different ids, which is an overwhelming majority of cases.

So, is there an option to lock using a parameter?

Thanks in advance.

解决方案

Double Checked Locking[^], sort of, does what I think you want.


这篇关于参数锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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