Click here to Skip to main content
15,867,957 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, is it possible to lock with parameters? Let me give you an example:

C#
// 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.
Posted

1 solution

Double Checked Locking[^], sort of, does what I think you want.
 
Share this answer
 
Comments
Jakub Janda 2-Dec-10 12:47pm    
Double checked locking would block ALL threads that read from database, not just those with the same cacheKey.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900