I have a buffer that needs to be locked sometimes, because 2 processes
update it.
Synclock (and the related Monitor.Enter) apply to multiple threads in one
process. If you are really dealing with two processes, you need to use a
mutex. If you are dealing with multiple threads within one process, then
read on.
My question is, what is Synlock protecting? Is it just protecting
MyBufferClass and all the members of MyBufferClass? Or could you have
code inside the sandwich that is totally unrelated like...
Synclock (and Monotor.Enter) assure that only one thread will be executing
at a time within Synclock'ed section(s) of code. When thread1 is executing
between Synclock xxx and its matching End Synclock, thread2 will block when
it attempts to execute Synclock xxx. Thread2's block will release when
thread1 executes End Synclock. What you do within the sections of code is up
to you, so the Synclock is not really protecting anything beyond enforcing
only one Synclock 'owner' of xxx. This notion is the same as with mutexes -
all they do is assure one 'owner' of the mutex at a time.
Imagine two subs that add and remove entries from some object of yours. No
problem if your program is single threaded. If it has multiple threads, all
will be well if you Synclock appropriately, eg
Dim MyObject As New SomeObjectClassYouWrote
Sub Add(whatever)
Synclock MyObject
whatever it takes to do an add goes here
End Synclock
End sub
Sub Remove(whatever)
Synclock MyObject
whatever it takes to do a remove goes here
End Synclock
End sub
The object being Synclock'ed could be the implied object (Me) if sub Add is
a method of class SomeObjectClassYouWrote, eg
Sub Add(whatever)
Synclock Me
whatever it takes to do an add goes here
End Synclock
End sub
In this case, if you have two object instances of SomeObjectClassYouWrote,
say o1 and o2, then calling o1.Add on one thread and calling o2.Add on
another thread would proceed without any blocking. On the other hand, if
both threads called o1.Add nearly simultaneously, then one would enter the
synclock, and the other would block.
Would "unrelatedvariable" be also protected from other processes
updating it?
No, if you followed the above. All mutexes and Synclocks do is enforce
taking turns. Remember, mutexes are for processes, and Synclocks are for
threads within processes.