1

I want to implement Singleton and found this acrticle from MSDN with several examples:

http://msdn.microsoft.com/en-us/library/ff650316.aspx

I have application that host WCF service. the application get String from Client, and sent this string to my Singleton. And from Singleton class i am open my Job class that do my stuff (open process..). The job class contain Event that each time process started to ends update my UI. and Singleton class should subscribe to this event. Also i am open new Singleton instance when my application start.

My service ServiceBehavior defined as ConcurrencyMode.Multiple and InstanceContextMode.PerSession so every client message create new instance:

[ServiceBehavior(
    ConcurrencyMode = ConcurrencyMode.Multiple,
    InstanceContextMode = InstanceContextMode.PerSession)]

so my only qustion is shold i use thread safe or non thread safe in my Singleton class ?

user2813889
  • 71
  • 1
  • 9

3 Answers3

2

Yes, a singleton should be thread safe.

Community
  • 1
  • 1
tom redfern
  • 30,562
  • 14
  • 91
  • 126
1

You should always opt for the thread-safe version when you are building something that can be modified. If it is a read-only collection then thread safety is not important.

Thread safety will incur a small performance cost usually due to locking, but it will save you a lot of potential pain later as race conditions are usually hard to debug.

Jun Wei Lee
  • 1,002
  • 11
  • 25
1

Thread unsafe may end up with weird results, possible to create more than 1 instance, which violates the singleton pattern. Thread Safe singleton is a good way to go.

Take a look to Jon Skeet's article, with different approach like Thread Safety, lazy instantiation etc.

http://csharpindepth.com/articles/general/singleton.aspx

C-va
  • 2,910
  • 4
  • 27
  • 42