How would you implement the Singleton design pattern in a thread-safe manner for this Logger class in a multi-threaded environment? Provide a code example in C#.
Loading
How would you implement the Singleton design pattern in a thread-safe manner for this Logger class in a multi-threaded environment? Provide a code example in C#.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Eliana BlakeRank #1,595 · 993 reputationPosted Apr 15, 2025, 1:11 PM EDT
Implementing the Singleton design pattern in a thread-safe manner is crucial to ensure that only one instance of the Logger class is created in a multi-threaded environment. One common approach to achieve thread safety in a Singleton implementation is by using double-check locking combined with the 'lock' keyword in C#. Here's a code example:
public class Logger { private static Logger instance; private static readonly object lockObject = new object(); private Logger() { } public static Logger GetInstance() { if (instance == null) { lock (lockObject) { if (instance == null) { instance = new Logger(); } } } return instance; } public void Log(string message) { // Logging implementation Console.WriteLine(message); } }In this code snippet, we use a lock to ensure that only one thread can create an instance of the Logger class at a time. The double-check locking pattern is used to avoid locking on every call to `GetInstance()` once the instance is already created.
By employing this approach, the Logger class can maintain a single instance in a thread-safe manner in a multi-threaded environment. This ensures that all threads access the same Logger instance without the risk of concurrency issues.
If you have any further questions or need additional clarification, feel free to ask!
Matthew Hess114 reputationPosted Apr 15, 2025, 2:41 PM EDT
Eliana's solution works but is overly complex. Here is a Microsoft article that explains a the preferred way to use a static initializers to implement the Singleton pattern in C#: Static Constructors - C# | Microsoft Learn
Here is the relevant code from the article. The key is that the private static field runs first ensuring that the field is instantiated before any caller accesses the instance.
public class Singleton { // Static field initializer calls instance constructor. private static Singleton instance = new Singleton(); private Singleton() { Console.WriteLine("Executes before static constructor."); } static Singleton() { Console.WriteLine("Executes after instance constructor."); } public static Singleton Instance => instance; }Code that needs to access the Singleton simply does this:
Singleton.Instance.