Re: SyncLock documentation
- From: Jack Jackson <jjackson@xxxxxxxxxxxxxxxx>
- Date: Thu, 27 Mar 2008 23:37:26 -0700
On Thu, 27 Mar 2008 18:20:01 -0700, AMercer
<AMercer@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
"Bob Altman" wrote:
"The lockobject expression should always evaluate to an object that belongs
exclusively to your class. You should declare a Private object variable to
protect data belonging to the current instance, or a Private Shared object
variable to protect data common to all instances.
You should not use the Me keyword to provide a lock object for instance
data.
It's a data encapsulation thing. If you use a private variable for your lock
object then you guarantee that callers won't be able to conflict with your lock.
But if you use a public object (your own class reference, for example) then code
outside of your class could cause your code to behave incorrectly.
And it's actually worse that "if", because most code that wants to create a
protected section locks on the object variable that is being protected. In
other words, I would typically write:
' Class data
Private m_yourClass As New YourClass
Sub X()
SyncLock m_yourClass
Do something with m_yourClass
End SyncLock
If your class uses Me as the lock object then you are using the same object that
I used, but for a completely different purpose.
Bob
In the example below, bbb uses 'synclock me', and ccc uses 'synclock sss'
where sss is an object created only for this purpose, as the documentation
suggests. I realize that sss is not exposed to the customer, but the
customer has a reference to the class, and that I refer to as Me. This is
the situation that I'm interested in, and I don't see any way that synclock
me causes things to "behave incorrectly". All I see is the potential for a
lock to be held longer than necessary. Other than this, bbb and ccc achieve
the same result. In a nutshell, I guess all that I am objecting to is the
existence of "Private sss As New Object" whose sole purpose is the SyncLock
statements in the class's methods.
Same question for you as for Tom Shelton - do you disapprove of 'Synclock Me'?
Public Class aaa
Public Sub bbb()
SyncLock Me
' stuff
End SyncLock
End Sub
Private sss As New Object
Public Sub ccc()
SyncLock sss
' stuff
End SyncLock
End Sub
End Class
What does SyncLock do if the same thread tries to lock something that
is already locked?
Your example exposes this possiblility:
Dim a As New aaa
SyncLock a
a.bbb()
End SyncLock
Even if that works, allowing external code to lock the object that is
used internally for locking makes me uncomfortable.
.
- References:
- SyncLock documentation
- From: AMercer
- Re: SyncLock documentation
- From: Bob Altman
- Re: SyncLock documentation
- From: AMercer
- SyncLock documentation
- Prev by Date: format in DGV
- Next by Date: Re: Close a form by pressing esc, how to do it without having a button
- Previous by thread: Re: SyncLock documentation
- Next by thread: Re: SyncLock documentation
- Index(es):