views:

65

answers:

2

I have a windows service hosting several WCF services. In my windows service I have couple objects with singleton behavior. This objects are accessible thru the WCF services from outside. A call can put a value into the objects and another call can retrieve this value.

Should I care about multithreading issues? I'm not starting any threads by myself. But anyway, should I do any locking when accessesing the singleton objects ? What about methods accessing the objects? Shouldn't they be marked as synchronized ?

EDIT Those objects are not singletons. The objects are created using IoC with singleton behavior.

+1  A: 

Yes, I think you should. And something very similar was asked not too long ago.

Object that is needed throughout the application

See this for some explanations

Implementing Singleton in C# , looking at Multithreaded Singleton.

Also Ist way of implementing Singleton Pattern in C#: looking at IIIrd way of implementing Singleton Pattern in C#: Simple Multithreaded Singleton Pattern and IVth way of implementing Singleton Pattern in C#: Multithreaded Singleton Pattern

astander
+1 Never mind the useful references, just simply for "Yes"
Kyle Rozendo
ifthe singleton ismutable, then just making the singleton pattern boilerplate code threadsafe is not going to help much. If he's doing things like the following (which I think he is), he has to make sure how to lock these reosurcesSingleton.Instance.AddSome(123,"some"); Singleton.Instance.GimmeSome(123);
Robert Giesecke
Yes, that is true.
astander
+2  A: 

Every call into your services is a thread of its own. So you are starting threads, quite a lot of them, even.

I am not going to discuss my stance on singletons etc. But, when you have shared mutable data, you have to think about how to protect it from concurrent access. If thread a puts something in there while thread b is looking for something, you might get unpredictable results.

The most obvious solution would be to use a lock for both reading and writing. Check out the docs to ReaderWriterLockSlim which should get you started.

Robert Giesecke
A friend of mine pointed me also to an Semaphore class in System.Threading. What do you think ? It looks like this class only control access to a pool of resources.
If you want to start out simple, you could just as easily use C#'s "lock" statement. Which is nothing more than syntactic sugar over the Monitor class. However, make sure not to make the instance you call lock on visible outside your singleton class, to prevent dead locking yourself.
Robert Giesecke