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