I have a test web service that I am calling asynchronously. I am surprised that it appears to work fine even though there is a (non-lazy) singleton in which the get method does not have a lock.
For example, my web service has a singleton that has a Get method (without a lock) that calls a previously set Factory, the factory then instantiates a new object from a pre-set detail object and returns the new object.
So the code would proceed as follows:
MethodCalledFromSingleton{
Instantiate Obj A
Use stored object to set properties of Obj A
Instantiate Object B
Assign Object B to a property of Object A
Return Object A
}
In an explicitly multi-threaded environment, one thread could instantiate the object, then before it returns, another thread could instantiate another object, then both return. Couldn’t both threads then point to the same reference?
However, as I said, I am not experiencing any problems, so do asynchronous web service calls conceptually work in a different way compared to explicitly threading the code?
It depends on what kind of asynchronous calls you are using. If you are using the event-based asynch pattern, synchronization is done automatically so that the completed event is run on the same thread that initiated the call.
I haven’t been able to find reliable documentation on it, but it is the behaviour I found out when digging into it, see What thread calls the completed event handler on silverlight WCF calls?.
Edit
Documentation validating that the completed event is called on the right thread can be found in the "Threading and Contexts" section of http://msdn.microsoft.com/en-us/library/ms228974.aspx.