.NET Force方法延迟执行

时间:2016-06-23 09:01:59

标签: c# .net linq dictionary deferred-execution

考虑以下情况

private static ConcurrentDictionary<string, ConcurrentDictionary<string, string>> CachedData;

其中多个线程通过调用

的方法访问此变量
ConcurrentDictionary<string, string> dic = CachedData.GetorAdd(key, HeavyDataLoadMethod())

此方法执行一些重量级操作以检索数据

private ConcurrentDictionary<string, string> HeavyDataLoadMethod()
{
        var data = new ConcurrentDictionary<string,string>(SomeLoad());
        foreach ( var item in OtherLoad())
           //Operations on data
        return data;
}

我的问题是,如果我使用GetorAddHeavyDataLoadMethod即使不需要也会被执行。

我想知道在这种情况下是否有某种方法可以利用延迟执行并使HeavyDataLoadMethod延迟,因此在真正需要之前不会执行。

(是的,我知道这就像用ContainsKey检查一样简单而忘了它,但我对这种方法很好奇)

1 个答案:

答案 0 :(得分:4)

您可以传递委托,而不是直接函数调用:

传入:

// notice removal of the `()` from the call to pass a delegate instead 
// of the result.
ConcurrentDictionary<string, string> dic = CachedData.GetorAdd(key, HeavyDataLoadMethod)

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".