If you have a shared (static) object in a class, and multiple threads handle this object, potentially at the same time, you might run into some problems. For example, let's say you have a shared collection of items. Now you might have a method to add an item, a method to remove an item, and a method to retrieve an item. But what happens when one thread removes the item that another thread is busy retrieving? You might get an "Index out of range" exception. But how can one prevent this? By using locks. In VB.NET, we have SyncLock. This is mainly used to prevent two threads or instances of a class running the same piece of code at the same time. But it can also be used to lock specific objects, so that only one thread or instance changes that object at a time. Let's look at an example.

Let's declare our shared object, and a special object, used to lock the critical parts.

   1: Private Shared ItemList As New ArrayList
   2: Private Shared LockObject As New Object

Next, let's setup some methods to handle this object.

   1: Public Sub AddItem(ByVal obj As Object)
   2:     SyncLock LockObject
   3:         ItemList.Add(obj)
   4:     End SyncLock
   5: End Sub
   6:  
   7: Public Function GetItem(ByVal i As Integer) As Object
   8:     SyncLock LockObject
   9:         If (i >= 0) And (i < ItemList.Count) Then
  10:             Return ItemList(i)
  11:         End If
  12:     End SyncLock
  13: End Function

The code will look similar to remove an item from the list.

The trick is to make the locking object shared as well. This means that when a thread wants to do anything to our shared object, it has to wait until LockObject is not locked by any other thread. That should prevent any conflicts.

If you have any suggestions about improving the code, or have an interesting thought, please leave a comment below.