Friday, June 17, 2005

Dotnet gotchas - 3

Synchronized collections are not synchronized on what you think they are, if you are coming from the java world. Consider the following piece of code:

Hashtable ht = Hashtable.Synchronized(new Hashtable());

addToTable(object o )
{
ht.Add(o, o);
}

processAll()
{
lock(ht)
{
// enumerate and do something with them. hold lock so that
// someone does not modify while you are enumerating...
}
}
The above code is incorrect since synchronised hashtables sync on an internal object called SyncRoot and not on the object itself!!

No comments: