CC# "Lock" equivalent in VB.NET?

  • Thread starter Thread starter Scott Johnson
  • Start date Start date
S

Scott Johnson

Hi

I am converting some code from C# to VB.NET and I have come across a command
that I can't find the VB equivalent. The C# command is 'lock' and I think
it is used to lock a data type from being used by other threads until it is
released. (?)

Here is the example:

lock(typeof(className))
{
if SkyIsBlue = True
{
//** Do somestuff in here
}
else
{
//** Run For Cover
//** Do somestuff in here
}
}

I tried to use lock, but it was only for locking files for reading/writing
and not the same. Is there an equivalent command in VB.NET or a way to
replicate it?

Thanks!
--Scott
 
The C# lock statement is equivelent to calling Monitor.Enter and
Monitor.Exit. So you can use those methods in VB.
 
* "Scott Johnson said:
I am converting some code from C# to VB.NET and I have come across a command
that I can't find the VB equivalent. The C# command is 'lock' and I think
it is used to lock a data type from being used by other threads until it is
released. (?)

'SyncLock'.
 
Marina,
Actually C# lock is equivalent to the VB.NET SyncLock statement as Herfried
indicated.

You are correct in that both implemented in terms of Monitor.Enter, however
they also both use a Try/Finally to be certain that the Exit is called!

I would recommend using SyncLock instead of Monitor.Enter directly, unless I
specifically needed Monitor.Enter.

Hope this helps
Jay
 
Back
Top