Miguel A. Arilla
Miguel A. Arilla

Reputation: 5344

.NET Force method deferred execution

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 HeavyDataLoadMethodgets 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 HeavyDataLoadMethoddeferred 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

Answers (1)

jessehouwing
jessehouwing

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())

That way you pass in the pointer to the method, instead of the method results. Your heavy data load method must accept a parameter with the value of "key".

Upvotes: 4

Related Questions