Thread-Safe Singleton Pattern Implementation in C#

Singleton Class Implementation

Implement a singleton pattern with lazy initialization:

public class Singleton
{
    private static Singleton _instance = null;

    private Singleton()
    {
        Console.WriteLine("Created {0}", GetType().Name);
    }

    public static Singleton GetInstance()
    {
        if (_instance == null)
            _instance = new Singleton();
        return _instance;
    }
}

Multithreaded Creation Approach

Demonstrate unsafe singleton creation using epxlicit threads:

Singleton s1 = null;
Singleton s2 = null;

Thread thread1 = new Thread(() => { s1 = Singleton.GetInstance(); });
Thread thread2 = new Thread(() => { s2 = Singleton.GetInstance(); });

thread1.Start();
thread2.Start();

thread1.Join();
thread2.Join();

Console.WriteLine("Same instance: {0}", ReferenceEquals(s1, s2));

Concurrent Loop Initialization

Create multiple instances using asynchronous invocations:

for (int i = 0; i < 2; i++)
{
    new Action(() => { Singleton.GetInstance(); }).BeginInvoke(null, null);
}

Thread.Sleep(1000);

Tags: C# Singleton Pattern multithreading Thread Safety

Posted on Wed, 09 Sep 2026 16:11:20 +0000 by The_Assistant