First of all, another thread cannot access the instance until the constructor is complete, since the instance itself will not be assigned until the constructor completes. In this case, another thread can access the variable that contains the instance until the constructor completes, but at this time it will be null . This would throw a NullReferenceException , but it would come from the instance access method, and not from the method inside the instance.
All this suggests that the only real solution I can see is to use an external lock that synchronizes the code when the instance is retrieved. If you are accessing a Hashset (or any other type in which an instance member is not guaranteed to be thread safe), you still need to lock operations.
Consider the following class as containing a reference to MyClass and the creator of other threads:
public class MasterClass { private MyClass myClass; private object syncRoot = new object();
This is a very (possibly overly) simplistic idea of how synchronization should happen, but the general idea of this approach is to wrap all the code that interacts with the shared object inside the lock block. You really need to learn how to write multi-threaded processes, as well as various approaches aimed at sharing resources between multiple threads.
EDIT
A completely different possibility is that instance variable values are cached depending on the stream. If you are not blocking (which creates a memory barrier), try marking the instance variable as volatile , which ensures that reads and writes will be performed in the correct order.
Adam robinson
source share