Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a lock statement in VB.NET?

Tags:

c#

vb.net

Does VB.NET have the equivalent of C#'s lock statement?

like image 229
iburlakov Avatar asked May 27 '09 13:05

iburlakov


People also ask

When would you use a lock statement?

The Lock statement is used in threading, that limit the number of threads that can perform some activity or execute a portion of code at a time. Exclusive locking in threading ensures that one thread does not enter a critical section while another thread is in the critical section of the code.

What is SyncLock?

The SyncLock statement ensures that multiple threads do not execute the statement block at the same time. SyncLock prevents each thread from entering the block until no other thread is executing it. The most common use of SyncLock is to protect data from being updated by more than one thread simultaneously.

Why should you avoid the lock keyword?

Avoid using 'lock keyword' on string object String object: Avoid using lock statements on string objects, because the interned strings are essentially global in nature and may be blocked by other threads without your knowledge, which can cause a deadlock.

What is lock used for in C#?

C# Lock keyword ensures that one thread is executing a piece of code at one time. The lock keyword ensures that one thread does not enter a critical section of code while another thread is in that critical section. Lock is a keyword shortcut for acquiring a lock for the piece of code for only one thread.


2 Answers

Yes, the SyncLock statement.

For example:

// C#
lock (someLock)
{
    list.Add(someItem);
}

// VB
SyncLock someLock
    list.Add(someItem)
End SyncLock
like image 169
Jon Skeet Avatar answered Oct 22 '22 19:10

Jon Skeet


It is called SyncLock example:

Sub IncrementWebCount()
    SyncLock objMyLock
        intWebHits += 1
        Console.WriteLine(intWebHits)
    End SyncLock
End Sub
like image 30
CSharpAtl Avatar answered Oct 22 '22 21:10

CSharpAtl