Dear ladies and sirs.
I would like to emply the if-lock-if pattern for checking if an object is present in the dictionary in a multithreaded environment. So, the code I am considering looks like so:
private IDictionary<string, SomeType> m_dic = new Dictionary<string, SomeType>();
private SomeType GetSomeObject(string key)
{
SomeType obj;
if (!m_dic.TryGetValue(key, out obj))
{
lock(m_dic)
{
if (!m_dic.TryGetValue(key, out obj))
{
m_dic[key] = obj = CreateSomeObject(key);
}
}
}
return obj;
}
I act on the assumption that even if another thread is inserting the object at the same key right now, the TryGetValue will not return a partially set reference (such thing does not exist in .NET, does it?), rather it will return null and so we enter the protected section and repeat the check.
My question is my assumption correct and the code is right?
Thanks.
EDIT
Let me throw in a restriction. The dictionary is actually a dictionary of singleton objects. So, once an entry is occupied, it is never changed. Just like the Instance property of a singleton - once it is set, it is never changed. Given that constraint, can we use the if-lock-if pattern?