Reputation: 3012
I'm confusing myself reading Microsoft's documentation on the Lazy<T>(bool) constructor.
The parameter is described as:
isThreadSafe: true to make this instance usable concurrently by multiple threads; false to make the instance usable by only one thread at a time.
If the code I would normally write in an accessor is:
If _rulesCache Is Nothing Then
SyncLock (_lockRulesCache)
If _rulesCache Is Nothing Then
_rulesCache = New RulesCache()
End If
End SyncLock
End If
Return _rulesCache
Do I want to use True or False in the constructor of the Lazy type?
Private _rulesCache As New Lazy(Of RulesCache)(**?**)
So my accessor becomes:
Return _rulesCache.Value
1) Once the object is created, it can handle multiple thread access internally.
2) I just need to make sure that if there are multiple threads hitting the accessor close to simultaneously and the object doesn't exist, that it only gets created once.
According to the documentation, statement 1 implies that the parameter should be false. Statement 2 implies that the parameter should be true.
I feel like I'm over-thinking this and it's just making me more confused. Or are the two statements above actually at odds with each other, and I should just stick with the manual locking to manage the object instantiation?
Upvotes: 1
Views: 154
Reputation: 71935
Statement 2 is the desired interpretation. The parameter does not affect any behavior of the object after the lazy initialization is complete; it only prevents two threads from accidentally racing and instantiating it twice. You can verify that in Reflector if you're curious.
Upvotes: 2