Reputation: 5344
Consider the following scenario
private static ConcurrentDictionary<string, ConcurrentDictionary<string, string>> CachedData;
where multiple threads access this variable via a method calling
ConcurrentDictionary<string, string> dic = CachedData.GetorAdd(key, HeavyDataLoadMethod())
where this method does some heavy weight operations to retrieve the data
private ConcurrentDictionary<string, string> HeavyDataLoadMethod()
{
var data = new ConcurrentDictionary<string,string>(SomeLoad());
foreach ( var item in OtherLoad())
//Operations on data
return data;
}
My problem here is that if I useGetorAdd
the HeavyDataLoadMethod
gets executed even if it is not needed.
I was wondering if there is some way to take advantage of deferred execution in this case and make the HeavyDataLoadMethod
deferred so it is not executed until it is really needed.
(Yes, I know this is as simple as checking with a ContainsKey and forget about it, but I'm curious about this approach)
Upvotes: 5
Views: 115
Reputation: 114857
You can pass a delegate, instead of the direct function call:
Either pass in:
// notice removal of the `()` from the call to pass a delegate instead
// of the result.
ConcurrentDictionary<string, string> dic = CachedData.GetorAdd(key, HeavyDataLoadMethod)
or
ConcurrentDictionary<string, string> dic = CachedData.GetorAdd(key,
(key) => HeavyDataLoadMethod())
Upvotes: 4