CodexBloom - Programming Q&A Platform

implementing Lazy Initialization of Singleton in .NET Core Leading to Unpredictable Behavior

👀 Views: 1460 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
c# .net-core singleton thread-safety C#

I just started working with I'm wondering if anyone has experience with I'm experiencing unexpected behavior when implementing a Singleton pattern with lazy initialization in my .NET Core 6 application. The intention was to create a thread-safe Singleton instance, but occasionally, I'm working with `NullReferenceException` when accessing properties of the instance. I implemented it like this: ```csharp public class Singleton { private static readonly Lazy<Singleton> instance = new Lazy<Singleton>(() => new Singleton()); public static Singleton Instance => instance.Value; private Singleton() {} public string SomeProperty { get; set; } = "Initial Value"; } ``` I access the Singleton like this: ```csharp public class SomeService { public void PerformAction() { var value = Singleton.Instance.SomeProperty; // Some processing... Singleton.Instance.SomeProperty = "Updated Value"; } } ``` The scenario seems to occur under heavy load when multiple threads access `PerformAction()` at the same time. Sometimes, the `SomeProperty` returns `null` or the `NullReferenceException` is thrown. I ensured that the instance is being accessed in a thread-safe manner, so I'm not sure where this might be going wrong. I've tried using `Interlock` to ensure thread safety around property access, but that hasn't resolved the scenario. Is there something I'm overlooking in my implementation? How can I ensure that the Singleton behaves reliably in a multi-threaded environment? This is for a microservice running on Debian. What are your experiences with this? For context: I'm using C# on Ubuntu 22.04. Cheers for any assistance!