synclock question

  • Thread starter Thread starter SD
  • Start date Start date
S

SD

I have a public object that I only want one thread to access at a time.
However the access to this object is not limited to one procedure. Will
SyncLock work in this case? If not what options do I have?

Thanks
SD

Code in Module

public A as Collection


Code in first file (this is a sub for a thread)
public sub1()

synclock A
A.add(.....)
end synclock

end sub


Code in another sub in another file for another thread

public sub2()

synclock A
'perform some operations on A
end synclock

end sub
 
Yes the this will work BUT variable A is has Public scope so any procedure
can change it not just those in the module where it is defined. This means
that some other piece of code outside of the module could access it without
a SyncLock and change it even if a thread has a SyncLock on it using one of
the module's thread safe procedures. This would have unexpected results.
Some further thought maybe required in the design of this portion of your
assembly.

--Robby
 
Thanks for the replies. I have made sure that every place where A is
accessed is in SyncLock blocks. But after reading more about SyncLock I
came across conflicting opinions as to the working of SyncLock. Some
said that SyncLock can only be used to Sync a block of code. Here I'm
attempting to sync several blocks of code by locking on one variable.
 
Cor said:
SD,

When I understand you well, than is that where Synclock is made for, be
aware that Synclock should be avoided as much as possible.

And what should I use instead?
 
SD,

When you need it, use it, however do not create it everywhere just because
that is easier or you are in doubt..

As alternative I try to keep values local in the thread and send the
resulting values to the main thread raising an event from that worker
thread.

However that is not always possible of course.

I hope this helps?

Cor
 
You are correct in stating "SyncLock can only be used to Sync a block of
code". This puts no limitions on how many SyncLocks you can put in your
code. You are SyncLocking two different pieces of code with two separate
SyncLocks using the same locking object. This is what SyncLock is designed
for and your use of it is perfectly legal and within the .Net guidelines.

--Robby
 
Robby said:
You are correct in stating "SyncLock can only be used to Sync a block of
code". This puts no limitions on how many SyncLocks you can put in your
code. You are SyncLocking two different pieces of code with two separate
SyncLocks using the same locking object. This is what SyncLock is designed
for and your use of it is perfectly legal and within the .Net guidelines.

--Robby
Thanks!
 
Back
Top