CC# "Lock" equivalent in VB.NET?

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
 
M

Marina

The C# lock statement is equivelent to calling Monitor.Enter and
Monitor.Exit. So you can use those methods in VB.
 
H

Herfried K. Wagner [MVP]

* "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'.
 
J

Jay B. Harlow [MVP - Outlook]

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
 

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