C# .NET强制方法延迟执行
考虑以下场景C# .NET强制方法延迟执行,c#,.net,linq,dictionary,deferred-execution,C#,.net,Linq,Dictionary,Deferred Execution,考虑以下场景 private static ConcurrentDictionary<string, ConcurrentDictionary<string, string>> CachedData; 私有静态ConcurrentDictionary缓存数据; 其中,多个线程通过调用 ConcurrentDictionary<string, string> dic = CachedData.GetorAdd(key, HeavyDataLoadMethod
private static ConcurrentDictionary<string, ConcurrentDictionary<string, string>> CachedData;
私有静态ConcurrentDictionary缓存数据;
其中,多个线程通过调用
ConcurrentDictionary<string, string> dic = CachedData.GetorAdd(key, HeavyDataLoadMethod())
ConcurrentDictionary 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;
}
私有ConcurrentDictionary HeavyDataLoadMethod()
{
var data=新的ConcurrentDictionary(SomeLoad());
foreach(OtherLoad()中的变量项)
//数据操作
返回数据;
}
我这里的问题是,如果我使用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 dic=CachedData.GetorAdd(键,HeavyDataLoadMethod)
或
ConcurrentDictionary dic=CachedData.GetorAdd(键,
(键)=>HeavyDataLoadMethod())
感谢您指出该方法的重载,这正是我们需要的
ConcurrentDictionary<string, string> dic = CachedData.GetorAdd(key,
(key) => HeavyDataLoadMethod())