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

  • Microsoft Revamps Fledgling AutoGen Framework for Agentic AI

    Only at v0.4, Microsoft's AutoGen framework for agentic AI -- the hottest new trend in AI development -- has already undergone a complete revamp, going to an asynchronous, event-driven architecture.

  • IDE Irony: Coding Errors Cause 'Critical' Vulnerability in Visual Studio

    In a larger-than-normal Patch Tuesday, Microsoft warned of a "critical" vulnerability in Visual Studio that should be fixed immediately if automatic patching isn't enabled, ironically caused by coding errors.

  • Building Blazor Applications

    A trio of Blazor experts will conduct a full-day workshop for devs to learn everything about the tech a a March developer conference in Las Vegas keynoted by Microsoft execs and featuring many Microsoft devs.

  • Gradient Boosting Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the gradient boosting regression technique, where the goal is to predict a single numeric value. Compared to existing library implementations of gradient boosting regression, a from-scratch implementation allows much easier customization and integration with other .NET systems.

  • Microsoft Execs to Tackle AI and Cloud in Dev Conference Keynotes

    AI unsurprisingly is all over keynotes that Microsoft execs will helm to kick off the Visual Studio Live! developer conference in Las Vegas, March 10-14, which the company described as "a must-attend event."

Subscribe on YouTube