wasAsked.

How do you handle thread safety in a singleton?

Routeware · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

First ask whether the singleton has mutable state. If it is stateless or immutable, it is automatically thread-safe. If it has state shared across requests, protect that state. 1. Make creation thread-safe - In ASP.NET Core, register it with AddSingleton; the DI container creates it once safely. - Without DI, use Lazy<T>, which is thread-safe by default: public sealed class ConfigCache { private static readonly Lazy<ConfigCache> _instance = new(() => new ConfigCache()); public static ConfigCache Instance => _instance.Value; private ConfigCache() { } } (A static readonly field initialised inline is also thread-safe, thanks to static initialisation guarantees. Avoid hand-written double-checked locking.) 2. Prefer immutable state Load data once and never mutate it, or replace the whole object atomically: private volatile IReadOnlyDictionary<string, Rate> _rates = new Dictionary<string, Rate>(); public void Refresh(IReadOnlyDictionary<string, Rate> fresh) => _rates = fresh; // atomic reference swap Readers always see either the old or the new complete dictionary. ImmutableDictionary or FrozenDictionary (.NET 8) work well here. 3. Use concurrent collections ConcurrentDictionary<TKey, TValue> for shared caches, with GetOrAdd and AddOrUpdate; ConcurrentQueue for queues. Note that GetOrAdd's value factory can run more than once under contention — wrap values in Lazy<T> if creation is expensive. 4. Use atomic operations for counters Interlocked.Increment(ref _count), Interlocked.CompareExchange for lock-free updates. 5. Use locks for compound operations private readonly Lock _gate = new(); // System.Threading.Lock in .NET 9+, or a private object lock (_gate) { _total += amount; _history.Add(amount); } Keep critical sections short, lock on a private object (never this or a type), and never await inside a lock. 6. Async critical sections Use SemaphoreSlim(1, 1) with WaitAsync and release in finally. 7. Avoid hidden shared state - Do not inject scoped services (DbContext) into singletons. - Do not store per-user or per-request data in singleton fields. - Shared non-thread-safe objects (some third-party clients) need protection or per-call instances. Test with concurrent load (parallel unit tests or load tests) because race conditions rarely appear in single-threaded testing.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics