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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With