Jake Freelander
Jake Freelander

Reputation: 1471

Is double synclock within the same thread ok?

I have a situation where multiple threads may access a class, the class consists of 3 private values and 6 properties that get/set various arithmetic combinations of the 3 values. Then I have 6 more properties that are just type conversions as they call on the first 6 properties as a part of their get/set operation.

All the get/set functions of the first 6 properties are synclocked to the same object. I wanted to synclock the get/set functions of the other 6 too to the same object since they use some of the same utility objects but it occurred to me that this will lead to synclocking the same object twice in a row.. sorta like this:

Private lock As New Object

Private _dCool As Double
Public Property dCool As Double
    Get
        SyncLock lock
            Return _dCool
        End SyncLock
    End Get
    Set(value As Double)
        SyncLock lock
            _dCool = value
        End SyncLock
    End Set
End Property

Public Property iCool As Integer
    Get
        SyncLock lock
            Return dCool
        End SyncLock
    End Get
    Set(value As Integer)
        SyncLock lock
            dCool = value
        End SyncLock
    End Set
End Property

There is no need to synclock iCool in this example but its just to illustrate the problem. As far as I've tested, there seem to be no problems with this but just wanted to ask if some problems i cant see right now could come up by doing this?

Upvotes: 0

Views: 699

Answers (1)

Hans Passant
Hans Passant

Reputation: 941605

Yes, not a problem. The VB.NET compiler generates calls to Monitor.Enter/Exit() when you use the SyncLock keyword, along with Try/Finally blocks to ensure that the entered monitor is always exited. The MSDN article for Monitor.Enter says:

It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.

Relevant phrase bolded. The Finally block ensure that the Exit() call requirement is always met.

Upvotes: 1

Related Questions