The code below is not thread-safe:
class SomethingWithLazyProperty { private OtherThing otherThing = null; public OtherThing OtherThing { get { if (this.otherThing == null) { this.otherThing = new OtherThing(); } return this.otherThing; } } }
As You may see when two threads enter the getter and the thread switching occures while
both of them are inside the if block two OtherThings will be instantiated and only
one of them will be stored in private field for later uses.
You should use some locking mechanism to avoid this race condition. The appropriate mechanism
may depend on the heaviness of instantiation. Lets choose lock to get out something more
of this example:
class SomethingWithLazyProperty { private object syncRoot = new object(); private OtherThing otherThing = null; public OtherThing OtherThing { get { lock(syncRoot) { if (this.otherThing == null) { this.otherThing = new OtherThing(); } } return this.otherThing; } } }
Thread-safety now in place, but the code will be really slow because of
locking every time we use this property. Thread-safety was only important
once at the begining but we slowed down the code for the whole lifecycle!
Modify a little bit the body of getter:
get { if (this.otherThing == null) { lock(syncRoot) { if (this.otherThing == null) { this.otherThing = new OtherThing(); } } } return this.otherThing; }
And voilá, the code is thread-safe and as fast as at the original!
How about Lazy?
Grrr… html escape….
So once again, how about Lazy: http://msdn.microsoft.com/en-us/library/dd642331(v=vs.110).aspx
Lazy appears first in .NET 4.0. ‘s LazyThreadSafetyMode.ExecutionAndPublication variant, which is using Monitor class to accomplish thread-safety which is same as the lock() statement does above.
The above pattern in means of synchronization is equvivalent with Lazy
But in code above You can decide to use something lightweighter lock mechanism, like SpinLock 🙂
The whole thing is about thinking behind the code. You may use that variant which You feel better in Your context.
Thanks.