Posted By

fraricce on 04/20/12


Tagged

safe singetonthread


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

cygnusfear
Priestd09


Thread-safe singleton pattern in C#


 / Published in: C#
 

Here's an implementation of a thread safe singleton

  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  

You need to login to post a comment.