I have a class which contains a Sync object
[DataContract]
class C1
{
[DataMember]
private object mySyncObject = new object();
}
This object was previously part of a DataContract which was serialized for no apparent reason. Since it contains no data I have omitted DataMember on the sync object. But since DataContractSerializer will not call the default ctor during deserialization this leads to NullReferenceExceptions at runtime when I use it.
lock(mySyncObject) // NullReferenceException
Now I would like to encapsulate the lock object access in a property and ensure that multithreaded access does not cause the property to return null or different objects.
My revised object now looks like
[DataContract]
class C1
{
private volatile object mySyncObject = new object();
object SyncObject
{
get
{
if (mySyncObject == null)
{
Interlocked.CompareExchange<object>(ref mySyncObject, new object(), null);
}
return mySyncObject;
}
}
}
Can it be so easy or have I missed a potential race condition here?