lundi 14 août 2023

How can I implement a thread-safe lazy-initialized singleton in C# without using the `Lazy

I've been reading about the Singleton pattern in C# and how thread safety can be a concern, especially when it comes to lazy initialization. I'm aware of the Lazy<T> class which can be used to create a thread-safe lazy-initialized singleton. However, for educational purposes, I'd like to understand how one might implement this without relying on Lazy<T>.

Here's what I've tried so far:

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}
  1. Is the above code a proper thread-safe lazy-initialized Singleton in C#?
  2. Are there potential pitfalls or performance concerns with this approach?
  3. Are there alternative methods to achieve this without Lazy<T>?

Any insights or suggestions would be appreciated!

Aucun commentaire:

Enregistrer un commentaire