Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static methods updating a Dictionary<T,U> in ASP.NET - is it safe to lock() on the dictionary itself?

I have a class that maintains a static dictionary of cached lookup results from my domain controller - users' given names and e-mails.

My code looks something like:

private static Dictionary<string, string> emailCache = new Dictionary<string, string>();

protected string GetUserEmail(string accountName)
{
    if (emailCache.ContainsKey(accountName))
    {
        return(emailCache[accountName]);
    }

    lock(/* something */)
    {
        if (emailCache.ContainsKey(accountName))
        {
            return(emailCache[accountName]);
        }

        var email = GetEmailFromActiveDirectory(accountName);
        emailCache.Add(accountName, email);
        return(email);
    }
}

Is the lock required? I assume so since multiple requests could be performing lookups simultaneously and end up trying to insert the same key into the same static dictionary.

If the lock is required, do I need to create a dedicated static object instance to use as the lock token, or is it safe to use the actual dictionary instance as the lock token?

like image 744
Dylan Beattie Avatar asked Dec 23 '10 13:12

Dylan Beattie


1 Answers

Collections in .NET are not thread safe so the lock is indeed required. An alternative to using the dictionary one could use Concurrent dictionaries introduced in .NET 4.0

http://msdn.microsoft.com/en-us/library/dd287191.aspx

like image 150
Elixir Avatar answered Oct 23 '22 15:10

Elixir