The_Black_Smurf
The_Black_Smurf

Reputation: 5269

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

Upvotes: 2

Views: 1611

Answers (3)

Guffa
Guffa

Reputation: 700372

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

Upvotes: 3

Marino Šimić
Marino Šimić

Reputation: 7342

There is probably some refactoring that would help avoid these situations. This code seems wierd. asigning to the lock variable an object if null and locking if not seems somehow wrong. Plus you lock and then change the lock variable!

Remember that locking goes to the reference not the value! Basically what it does is block acess to the specified reference from all blocks of code not inside the lock.

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273274

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.

Upvotes: 4

Related Questions