0

I have a "recipe popup" where the user can can multiple instances. Every popup has a collection of images. Both recipes can have cut volumes of images. These images are rendered from svg. To reduce memory/cpu usage, I want to make a kind of "image cache" (static class with a collection of rendered svgs).

The Problem: If recipe1 has ImageA and ImageB, recipe2 has ImageB and ImageC, then only ImageA should be destroyed/disposed (removed from the collection) after recipe1 has closed.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Dominic Jonas
  • 4,717
  • 1
  • 34
  • 77
  • 1
    You could use list of [weak references](https://msdn.microsoft.com/en-us/library/gg712738(v=vs.110).aspx) to images. – dbc Sep 26 '16 at 06:26
  • 1
    Please clarify why regular cache classes do not work for your case (which you presumably tried already). – Alexei Levenkov Sep 26 '16 at 06:30
  • 2
    Wouldn’t the purpose of a cache be to not destroy ImageA, so it is still there once you get back to recipe1? – poke Sep 26 '16 at 06:33
  • @AlexeiLevenkov This is the first time that I hear something about a cache class. at_poke A recipe can have about 100-200 different svg images. So I don't know how much ram will be used, if the user opens 10 recipes. To prevent this trouble, I want to share the rendered images like KooKiz said. – Dominic Jonas Sep 26 '16 at 06:42
  • Expanding on the weak reference idea, see [Presenting WeakDictionary](https://blogs.msdn.microsoft.com/nicholg/2006/06/04/presenting-weakdictionarytkey-tvalue/) and [Good implementation of weak dictionary in .Net](http://stackoverflow.com/questions/2784291/good-implementation-of-weak-dictionary-in-net). – dbc Sep 26 '16 at 06:49
  • @dbc weak references are not going to give OP precise control they are looking for. Otherwise regular cache (`MemoryCache`) would be fine and easier to get right... Not really sure what benefits you see of using weak references over existing cache. – Alexei Levenkov Sep 26 '16 at 06:51
  • @AlexeiLevenkov - If I understand OP correctly, the requirement is to reduce memory usage by not duplicating images in memory when used in multiple locations, but that automatically allows an image to be finalized when it is no longer used anywhere. Weak dictionary enables this. But I could be wrong in my understanding of OP's requirement. – dbc Sep 26 '16 at 06:56

1 Answers1

1

The purpose of a cache is to hold elements, which are currently not in use, but probably needed in the near future and make their access faster.

So why don't you use the MemoryCache with a SlidingExpiration like described in this answer? That way all images, that haven't been loaded for a while, will be removed.

Community
  • 1
  • 1
Oliver
  • 43,366
  • 8
  • 94
  • 151