Thread-safe singleton pattern in C#


/ Published in: C#
Save to your folder(s)

Here's an implementation of a thread safe singleton


Copy this code and paste it in your HTML
  1. public sealed class MySingleton
  2. {
  3. private static MySingleton instance;
  4. private static readonly Object sync = new object();
  5.  
  6. private MySingleton()
  7. {
  8. // initialize members here
  9. }
  10.  
  11. public static MySingleton Instance
  12. {
  13. get
  14. {
  15. if (instance == null)
  16. {
  17. lock (sync)
  18. {
  19. if (instance == null)
  20. instance = new MySingleton();
  21. }
  22. }
  23.  
  24. return instance;
  25. }
  26. }
  27.  
  28. public void SayHello()
  29. {
  30. Console.WriteLine("Hello!");
  31. }
  32.  
  33. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.