I've profiled my application and ran some performance tests which led me to believe that the following if-lock-if arrangement:
private float GetValue(int id)
{
float value;
if (!dictionary.TryGetValue(id, out value))
{
lock (lockObj)
{
if (!dictionary.TryGetValue(id, out value))
{
value = ComputeValue(id);
dictionary.Add(id, value);
}
}
}
}
seems to perform faster than "lock-if" or using ReaderWriterLockSlim. But very rarely, I get the following exception:
1) Exception Information
*********************************************
Exception Type: System.NullReferenceException
Message: Object reference not set to an instance of an object.
Data: System.Collections.ListDictionaryInternal
TargetSite: Int32 FindEntry(TKey)
HelpLink: NULL
Source: mscorlib
StackTrace Information
*********************************************
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
at MyNamespace.GetValue()
.....
.....
What am I doing wrong here ?
Edit: To clarify, this method is called on average more than 50 million times, and the conflict is generally less than 5,000.
Thanks