A singleton is a class that allows exactly one instance of itself and gives everyone access to it through a static property. The hard part is creation: if two threads ask for the instance at the same moment, a careless implementation creates two.
In current .NET, Lazy<T> solves this in three lines.
The Lazy<T> version
public sealed class Singleton
{
private static readonly Lazy<Singleton> _instance = new(() => new Singleton());
public static Singleton Instance => _instance.Value;
private Singleton()
{
Console.WriteLine("Instance created");
}
}
Testing it from many threads at once:
var instances = new Singleton[10];
Parallel.For(0, instances.Length, i => instances[i] = Singleton.Instance);
Console.WriteLine(instances.All(s => ReferenceEquals(s, instances[0])));
Output:
Instance created
True
The constructor runs once, and all ten threads get the same object.
How it works: by default, Lazy<T> uses LazyThreadSafetyMode.ExecutionAndPublication. The first thread to read Value runs the factory; any other thread that arrives meanwhile waits for it and then gets the same result. After that, reading Value costs about as much as reading a field. The instance is created on first use, not when the program starts, and Lazy<T> handles all the memory-ordering details that make hand-written versions fragile.
The other parts matter too. The private constructor stops other code from calling new Singleton(). sealed stops a subclass from adding a second way in.
An even simpler version
If you do not need precise control over when the instance is created, a static read-only property is enough:
public sealed class Singleton
{
public static Singleton Instance { get; } = new();
private Singleton() { }
}
The runtime guarantees that a type’s static initializers run exactly once, under a lock, so this is thread-safe too. The difference is timing: the runtime may run the initializer earlier than the first access to Instance, for example when another static member of the class is used. For a singleton with a cheap constructor, that does not matter and this is the version to prefer.
The double-checked locking version
Older code, including the original version of this post, often builds the same thing by hand:
public sealed class Singleton
{
private static volatile Singleton? _instance;
private static readonly object _syncRoot = new();
private Singleton() { }
public static Singleton Instance
{
get
{
if (_instance is null)
{
lock (_syncRoot)
{
if (_instance is null)
_instance = new Singleton();
}
}
return _instance;
}
}
}
The first check avoids taking the lock once the instance exists. The second check, inside the lock, handles two threads that both passed the first check. volatile stops another thread from seeing a reference to an object whose constructor has not finished running. Remove any one of the three and the code has a race condition that may only show up under load. This version is correct, but there is nothing to gain from writing it today: Lazy<T> does the same job and is harder to get wrong.
Traps
Exceptions are cached. If the factory passed to Lazy<T> throws, the default mode remembers the exception and rethrows it on every later access to Value. The singleton can never be created in that process. If creation can fail for a temporary reason, such as a network call, either move that work out of the constructor or use LazyThreadSafetyMode.PublicationOnly, which does not cache exceptions (but may run the factory on several threads at once and keep only the first result).
Thread-safe creation is not a thread-safe object. All the patterns above only guarantee that one instance is created. If the singleton holds mutable state, such as a dictionary or a counter, every method that touches that state still needs its own synchronization, or a concurrent collection.
Singletons are hard to test. Code that calls Singleton.Instance directly cannot be given a fake in a unit test, and state leaks between tests that run in the same process.
Prefer dependency injection in applications
In ASP.NET Core, worker services and any app that uses Microsoft.Extensions.DependencyInjection, register the class as a singleton and let the container create it:
builder.Services.AddSingleton<IClock, SystemClock>();
The container creates one instance in a thread-safe way, consumers receive it through their constructors, and tests can register a different implementation. The class itself stays an ordinary class with a public constructor. Keep the static Instance pattern for libraries and small tools that have no container.
1 thought on “Thread-Safe Singleton Pattern in C# Using Lazy”