Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 777
The_Black_Smurf Avatar asked Aug 25 '26 20:08

The_Black_Smurf


2 Answers

Yes, use a Helper object.

You shouldn't assign to myObjectA anyway when it's used as a Lock.

From MSDN:

Lock Object Value. The value of lockobject cannot be Nothing. You must create the lock object before you use it in a SyncLock statement.

You cannot change the value of lockobject while executing a SyncLock block. The mechanism requires that the lock object remain unchanged.

like image 72
Henk Holterman Avatar answered Aug 28 '26 13:08

Henk Holterman


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
like image 38
Guffa Avatar answered Aug 28 '26 13:08

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!