I’m working with a WPF application tasked with displaying a large amount of bitmap files. In the future I plan to implement a solution using vector graphics, but for now I have this problem:
To minimize the time my application reads files from disk I created a Dictionary<string, BitmapImage> (where string is the file path of the image) to hold the most lately used images. If an image is requested that was recently viewed, the program fetches it from the Dictionary instead of from the disk. However, as the number of images viewed grows, so does the amount of RAM used by the program. So my idea was holding a limited amount of images, and as a new one is loaded from disk, overwrite the oldest one from my Dictionary.
How would I go about doing this in the best way possible? I’ve looked into using a SortedDictionary but can’t figure out how to write an IComparer as neither the keys or items have any information about the time/order they were added.
Would keeping a separate SortedDictionary<DateTime, string> with a DateTime IComparer be a sensible solution? In that way, when a new file is added the path to the oldest added file can be found, and matched with the correct image in my Dictionary. This kind of feels like a to advanced solution though. Any overlooked or built-in solutions?
It sounds like you want a least recently used (LRU) cache (“discards the least recently used items first”). There are a few implementations floating around on the web: