synclock question

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
 
R

Robby

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
 
S

SD

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.
 
S

SD

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?
 
C

Cor Ligthert

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
 
R

Robby

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
 
S

SD

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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top