I profiled my application and performed some performance tests, which led me to think that the following if-lock-if scheme:
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 be 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?
Change To clarify, this method is called on average more than 50 million times, and the conflict is usually less than 5000.
thanks
source share