Practical .NET

Build Your Own ASP.NET Cache with WeakReferences

You want to keep an object around only as long as you have memory available, do ya? Then you need the WeakReference class.

I very much like the ASP.NET Cache and the more generally usable MemoryCache collections: They let me build up a set of objects (typically drawn from a database) that I can use in my application. Of course, those objects take up room in memory, which is too bad -- especially if the computer is running short on memory. However, the nice thing about these two caching objects is that they discard items in the collection when memory gets tight.

This does mean that you always have to check if an object is still there when you go to retrieve it from either of the caches. Fortunately, it also means that, as long as you have memory to spare, you then can put that memory to good use.

If you want to create your own cache, you can do that using the WeakReference class. A WeakReference object holds some other object but doesn't stop the .NET runtime from garbage collecting that other object. However, if the other object is garbage collected, the WeakReference object remains around for you to work with.

You can check to see if the object is still there by using the WeakReference object's IsAlive property; if the other object is still present, you can retrieve it through the WeakReference object's Target property.

The following code creates a Dictionary of WeakReference objects holding Salesorder objects with each Salesorder stored in the Dictionary with the key of the Salesorder's CustomerId (I discussed the ToDictionary method in an earlier tip):

soCache = Dictionary(Of String, WeakReference)
soCache = (from so in db.Salesorders
           select new WeakReference(so)).ToDictionary(
wkSo => ((Salesorder)(wkSo.Target)).CustomerId);

Now, if I want to retrieve the Salesorder from the Dictionary, I can just ask for it by key value. If the Salesorder has been garbage collected, I can retrieve it from the database. Here's code getting the Salesorder for customer A123 from my self-constructed cache:

Salesorder sord;
if (custCache["A123"].IsAlive){
   sord = (Salesorder) custCache["A123"].Target;}
else {
   sord = db.Salesorders.Where(so => so.CustomerId == "A123").FirstOrDefault()}

There's also a generic version of the WeakReference object (with a very different interface) that lets you specify the type of the other object.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

Subscribe on YouTube