Suppose you need a complex/slow process for generating something and you want to cache it. But you don’t know if that something will be used a lot of just a few times. If it is the last case, you don’t care executing again the process, but it’s different if it’s accessed several times.
WeakDictionary to the rescue!
This dictionary, basically, maintains each value in a class that could reference it as a weakreference if it wasn’t accessed often and if the amount of items is bigger than a threshold defined:
var d = new WeakDictionary<int,SomeClass>(3); d.Add(1, new SomeClass()); d.Add(2, new SomeClass()); d.Add(3, new SomeClass()); //We use the values... var bla = d; var bla1 = d; var bla2 = d; var bla3 = d; var bla4 = d; var bla5 = d; //When we try to add an item and we are passing the threshold, it will weak the less used reference d.Add(4, new SomeClass());
d value is now maintained with a weak reference. If it’s used before it’s garbage-collected, it will be alive again and d will be the “weak one”.
You can download the code here.