Search code examples
.netvb.netsynclock

SyncLock on null object


Is there simple way to SyncLock an object that can be null?

And before you ask for it, yes, I know that it isn't logical to perform a SyncLock on a null variable. However, that would simplify my code because right now, I have no choice but to perform a null check all over the place before calling a SyncLock.

If myObjectA Is Nothing Then
  myObjectA = myObjectB
Else
  SyncLock myObjectA
    myObjectA = myObjectB
  End SyncLock
End If

Solution

  • No, you can't use a null reference as identifier for a lock.

    You can't even use a reference as identifier if it can be null, so your current code is not thread safe. You have to use a different way to identify the lock. Two different threads can replace the null reference without being able to exclude each other, which would cause one reference to be overwritten by the other:

    If myObjectA Is Nothing Then
      ' Here another thread can change the reference, believing that it's safe
      myObjectA = myObjectB
    Else
      SyncLock myObjectA
        myObjectA = myObjectB
      End SyncLock
    End If