Static methods for updating the dictionary <T, U> in ASP.NET - is it safe to block () in the dictionary itself?

I have a class that supports a static dictionary of cached search results from my domain controller - usernames and emails.

My code looks something like this:

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 locking required? I guess, since multiple queries can search at the same time and end up trying to insert the same key in the same static dictionary.

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

+5
6

, , / .

, , . , . , .

+1

.NET , . Concurrent dictionaries, .NET 4.0

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

+5

.

, , , .

, object lock =new object(); .

+1

, . ( ) , , , . .

, , , , Add, . .

UPDATE: Insert , Item, Add. , set "" false, "" "" true:

if (add)
{
    ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}

, , ( ), .

+1

MSDN , lock() , .

I would rather use an instance of the object rather than the object you are trying to modify, especially if this dictionnary has accessors that allows external code to access it.

Maybe I'm wrong, I haven't written a C # line since a year ago.

+1
source

As far as I could see, an extra was used objectas a mutex:

private static object mutex = new object();

protected string GetUserEmail(string accountName)
{
    lock (mutex)
    {
        // access the dictionary
    }
}
0
source

All Articles