2016-06-23 10 views
5

इस परिदृश्य पर विचार करेंनेट सेना विधि आस्थगित निष्पादन

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; 
} 

मेरी समस्या यह है कि यदि मैंका उपयोग करता हूंHeavyDataLoadMethod निष्पादित हो जाता है भले ही इसकी आवश्यकता न हो।

मैं सोच रहा था कि इस मामले में स्थगित निष्पादन का लाभ उठाने का कोई तरीका है और HeavyDataLoadMethod स्थगित कर दिया गया है, इसलिए इसे वास्तव में आवश्यक होने तक निष्पादित नहीं किया जाता है।

(हाँ, मैं जानता हूँ कि यह एक ContainsKey साथ जाँच और इसके बारे में भूल जाते हैं के रूप में सरल है, लेकिन मैं इस दृष्टिकोण के बारे में उत्सुक हूँ)

उत्तर

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

+0

विधि के अधिभार को इंगित करने के लिए धन्यवाद, बस क्या आवश्यक है –

संबंधित मुद्दे