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

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube