Search code examples
c#singletonbufferimage-caching

How to improve performance for oftenly using bitmaps in c#?


I am trying to make an image checker. Basically it checks a big image (usually changes) contain an img (never changes) or not. So, to imporve performance, i'm looking for a way to keep this image on memory so i don't go to the disc everytime for it.

Bitmap img = Accord.Imaging.Image.FromFile(@"D:\img.png");

Is there any good solution for this? Singleton pattern is good choice for me? Any running examples?

EDIT-1: WPF project.

Thanks in advice!


Solution

  • Basically it would be best to avoid using static/singleton patterns (as always it's best to avoid using them). You could write some Repository with this Bitmap loaded in the creation and then store it in some higher-level of the classes you're using. But sometimes it's a good way to check the Singleton :) Here is a basic thread-safe singleton pattern (with Bitmap inside):

    class Singleton
    {
        public Bitmap Image { get; set; }
    
        private Singleton() { }
    
        private static Singleton _instance;
    
        private static readonly object _lock = new object();
    
        public static Singleton GetInstance(Bitmap value = null)
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new Singleton();
                        if (value != null)
                        {
                          _instance.Image = value;
                        }
                    }
                }
            }
            return _instance;
        }     
    }
    

    (Taken from one of the best pages in Software Development snippets: https://refactoring.guru/design-patterns/singleton/csharp/example#example-1)

    Then your first load would be:

    var  singleton = Singleton.GetInstance(Accord.Imaging.Image.FromFile(@"D:\img.png"));
    

    And each next:

    var image = Singleton.GetInstance().Image;