Suppose I have the following object
public class MyClass { public ReadOnlyDictionary<T, V> Dict { get { return createDictionary(); } } }
Suppose ReadOnlyDictionary
is a read-only wrapper around Dictionary<T, V>
.
The createDictionary
method takes considerable time to complete and return the dictionary is relatively large.
Obviously, I want to implement some kind of caching so that I can reuse the result of createDictionary
, but also do not want to abuse the garbage collector and use a lot of memory.
I thought of using WeakReference
for a dictionary, but not sure if this is the best approach.
What would you recommend? How to correctly process the result of an expensive method that can be called several times?
UPDATE:
I'm interested in advice for the C # 2.0 library (one DLL, not visual). The library can be used on the desktop of a web application.
UPDATE 2:
The question also applies to read-only objects. I changed the property value from Dictionary
to ReadOnlyDictionary
.
UPDATE 3:
T
is a relatively simple type (for example, a string). V
is a custom class. You can assume that instance V
is expensive to create. A dictionary can contain from 0 to several thousand elements.
It is assumed that the code is accessible from one thread or from several threads with an external synchronization mechanism.
I am fine if the GC-ed dictionary when no one uses it. I am trying to find a balance between time (I want to somehow cache the result of createDictionary
) and memory costs (I do not want the memory to take longer than necessary).