Question

MS reference: http://msdn.microsoft.com/en-us/library/3a86s51t(v=vs.71).aspx

"The type of the expression in a SyncLock statement must be a reference type, such as a class, a module, an interface, array or delegate."

Scenario: Multiple threads reading and editing a list.

I know this will avoid a race condition:

SyncLock TheList
TheList.item(0) = "string"
End SyncLock

But will this?

SyncLock TheList.item(0)
     TheList.item(0) = "string"
End SyncLock
Was it helpful?

Solution

No, your second snippet is fundamentally wrong. Since you are replacing the object that you lock on. So another thread is going to take the lock on another object, you therefore have no thread-safety at all. A lock can only work if threads use the exact same object to store the lock state.

Notable too is the kind of object you take the lock on. Your second snippet does so on an interned string. Very, very bad since is very likely to cause deadlock. Any other code anywhere else might be wrong the same way and also take a lock on a string literal. If that happens to be "string" as well, you'll easily get completely undiagnosable deadlock.

Also the problem with your first snippet, other code might be taking a lock on the TheList object since it is probably public. Producing deadlock for the same reason. Boilerplate is that you always use a dedicated object to store the lock state that isn't used for anything else, only ever appearing in any code that accesses the list.

 Private ListLock As Object = New Object
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top