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

  • Creating Reactive Applications in .NET

    In modern applications, data is being retrieved in asynchronous, real-time streams, as traditional pull requests where the clients asks for data from the server are becoming a thing of the past.

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

  • .NET 9 Preview 3: 'I've Been Waiting 9 Years for This API!'

    Microsoft's third preview of .NET 9 sees a lot of minor tweaks and fixes with no earth-shaking new functionality, but little things can be important to individual developers.

  • Data Anomaly Detection Using a Neural Autoencoder with C#

    Dr. James McCaffrey of Microsoft Research tackles the process of examining a set of source data to find data items that are different in some way from the majority of the source items.

Subscribe on YouTube