Tuesday, November 3, 2009

'SyncLock' operand cannot be of type '' because '' is not a reference type

Just had this little error in VB.NET:

Error Message: 'SyncLock' operand cannot be of type 'Boolean' because 'Boolean' is not a reference type.
Error ID:

I tried to change the variable to type Object, but this seems to be converted to Boolean during runtime, which raises the same error.

A clumsy way around this is to simply use a Boolean array of length 1. There must be a better way though, and I'll update this post when I find a better approach.

Yes, I did say vb. Yes, I am ashamed. Client's request.

Ok here's the deal on using SyncLock or Monitor.Enter (mutex) with value types such as Boolean, Integer, or Double. One is not supposed to lock value types, as they do not have the necessary overhead fields (MethodTablePointer and SyncBlockIndex) to allow a lock to be acquired. One gets around this issue, by creating a reference type, which acts as a flag when the value type is being written to. More on this at the end of Jeffery Richter's article on Safe Thread Synchronization.

No comments: