Home > C# > Weak Dictionaries

Weak Dictionaries

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[1];
var bla1 = d[1];
var bla2 = d[1];
var bla3 = d[2];
var bla4 = d[2];
var bla5 = d[3];

//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[3] value is now maintained with a weak reference. If it’s used before it’s garbage-collected, it will be alive again and d[2] will be the “weak one”.

You can download the code here.

Categories: C# Tags: ,
  1. Shlomi
    May 16, 2011 at 5:22 am

    Nice idea!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: