tags:

views:

42

answers:

1

Sample One

Public _objLock As Object = New Object
Public ReadOnly Property MyObjects() As IEnumerable(Of Object)
    Get
        SyncLock _objLock
            If _myObjects Is Nothing Then
                _myObject = LoadMyObjects()
            End If
            Return _myObjects
        End SyncLock
    End Get
End Property

Sample Two

Public _objLock As Object = New Object
Public ReadOnly Property MyObjects() As IEnumerable(Of Object)
    Get
        SyncLock _objLock
            If _myObjects Is Nothing Then
                _myObject = LoadMyObjects()
            End If              
        End SyncLock
        Return _myObjects
    End Get
End Property

Will there be any ifference between these implementations ?

+4  A: 

No, returning inside a lock makes no difference. Once you leave the lock, it will cease to exist.

Kevin
Is there any benefit to have the lock object to shared rather than a member variable ?
Joker
Locks are only good for things that have access to the same lock. If objects A and B have their own member variable lock, A will lock on it's lock, and B will lock on it's lock.
glowcoder
Sharing the same lock object reduces the number of independent locks, so it can reduce the risk of getting into a deadlock situation - thread A takes lock 1, then tries to take lock 2. Thread B takes lock 2, then tries to take lock 1. If the timing is right, these two threads will wait forever for the other lock to be released. When working with multiple locks, you must be careful that all uses of the multiple locks always take the locks in the same order. This becomes more difficult as the number of locks increases.
dthorpe
The general rule of thumb is that you only need one lock per object instance to protect the object instance from being called by multiple threads at the same time. Sharing the same lock object between different instances can also work, but is probably overkill since most of the time what you're trying to protect is multithread access to the private data of a single object instance.
dthorpe