Dennis said:
If I understand you correctly, then if I have a value type variable in my
module from which I start a thread that access the value type variable,
synclock won't work on the value type variable and both the thread and module
procedures can access the variable at the same time?
No, you're misunderstanding the use of SyncLock. VB won't even compile
a SyncLock to a value type.
What SyncLock does is to keep threads waiting for a given "lock", as
long as that "lock" is in use. It does nothing to prevent different
threads from acessing this or that variable.
In other words, it's like if your thread locked itself into a closet
where no other thread can enter because only it (the thread) has the
key. All will go well if every thread wait for the key to enter the
closet. But if any of your threads pretend that they're Neo and realize
that "there's no closet", then all sorts of weird things may happen.
So, you *will* use SyncLock to prevent simultaneous access to a given
variable (or group of variables) if you only access the variable(s)
when you (the thread) have the lock.
It turns out that the lock must be a reference-type variable.
Ex:
Private mLock As New Object
Private Structure Info
Name As String
Age As integer
End Structure
Private mValue As Info
'...
Sub DoThis
'...
SyncLock mLock
mValue.Name = "Carlos"
mValue.Age = 15
End SyncLock
'...
End Sub
Sub DoThat
'...
SyncLock mLock
mValue.Name = "Rita"
mValue.Age = 42
End SyncLock
'...
End Sub
Sub DoBlah
'...
Dim Value As Info = mValue
'...
End Sub
If you have a thread running on DoThis and another on DoThat, and they
both ask for the same lock (mLock, in the example) to access mValue,
then you're guaranteed that the value of mValue will be consisitent. On
the other hand, if you break this protocol (as DoBlah does), of not
using the same lock when accessing variables shared by different
threads, then you lose all guarantees of integrity (in this case, the
mValue seen by DoBlah may be completely inconsistent).
To preserve the integrity, all points of your code that may be running
in separate threads must keep the protocol: only access a given set of
variables after acquiring the pertinent lock.
Ex:
Sub DoBlah
'...
Dim Value As Info
SyncLock mLock 'Now I may do whatever I want
Value = mValue
End SyncLock
'...
End Sub
Hope this helped.
Regards,
Branco.