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

comments powered by Disqus


  • Microsoft's Tools to Fight Solorigate Attack Are Now Open Source

    Microsoft open sourced homegrown tools it used to check its systems for code related to the recent massive breach of supply chains that the company has named Solorigate.

  • Microsoft's Lander on Blazor Desktop: 'I Don't See a Grand Unified App Model in the Future'

    For all of the talk of unifying the disparate ecosystem of Microsoft-centric developer tooling -- using one framework for apps of all types on all platforms -- Blazor Desktop is not the answer. There isn't one.

  • Firm Automates Legacy Web Forms-to-ASP.NET Core Conversions

    Migration technology uses the Angular web framework and Progress Kendo UI user interface elements to convert ASP.NET Web Forms client code to HTML and CSS, with application business logic converted automatically to ASP.NET Core.

  • New TypeScript 4.2 Tweaks Include Project Explainer

    Microsoft shipped TypeScript 4.2 -- the regular quarterly update to the open source programming language that improves JavaScript with static types -- with a host of tweaks including a way to explain why files are included in a project.

Upcoming Events