Tuesday, November 21, 2006

Syncronizing access against a value type using Monitors (Why Monitors dont work with Value Types)

Suppose I want to syncronize access against an integer. I naturally cover the code block with the variable I need syncronization on. So I write something as follows:
C#
lock(x) //x is an integer
{
//blah blah code
}
VB.NET
SyncLock x
' Blag Blah code
End SyncLock
Whoa! the compiler throws a syntax error
'int' is not a reference type as required by the lock statement.
What on earth is wrong with the compiler???? Why wouldnt it accept value types.
Before we jump into deep valleys of nitty gritty details I'll just let you know the work around for the busy types. Hmm.. now when I think about it there's no work around. Either use the boxed type of the variable or use typeof(x) as a parameter in the lock statement. (Using typeof(x) will guard the code block against all variable of type int. Sometimes it may create more problems). Wow I bet you must have developed serious doubts about my authenticity as a .NET programmer. But that cannot be demotivating enough for me. I'll carry on....

Digging Deeper

First a litlle bit about reference types. Following diagram depicts what i really thought objects in memory look like:
[Important things first - I made those graphics :) Take your time to appreciate those.]
But I soon realized that there should be more than this to objects that aids thread synchronization which is not present in value types. I was right!!! An object in memory actually looks like following:

This Sync Block is used for syncronization. As this is not present in value types lock(x) returns a syntax error. Btw, why the hell did they put sync block before the actual address??? They outta be more intelligent than me. Any ideas???