.NET Force 方法延迟执行

.NET Force method 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;
}

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

我想知道在这种情况下是否有某种方法可以利用延迟执行并使 HeavyDataLoadMethod延迟,以便在真正需要时才执行。

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

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

要么传入:

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