I went through the implementation of SyncHashtable in defined in .Net framework BCL.
This class provides synchronized access to multiple readers and writers.
One of the methods is implemented as
public override Object this[Object key] {
get {
return _table[key];
}
set {
lock(_table.SyncRoot) {
_table[key] = value;
}
}
}
In my opinion the get method should also have a lock on Syncroot before accessing the object.
Consider the scenario :
Thread 1 : Deleting keys from the Hashtable.
Thread 2 : Reading objects using keys.
If a context switch occurs in thread 2 while reading the object and if thread 1 deletes the object , then in such a case the read operation will fail or give inconsistent result.
Hence couldn’t we implement this method like this
public override Object this[Object key] {
get {
lock(_table.SyncRoot)
{
return _table[key];
}
}
set {
lock(_table.SyncRoot) {
_table[key] = value;
}
}
}
Thanks
Vivek
Locking the
Hashtablefor reading is not necessary because that is already thread safe under these circumstances.The documentation for
Hashtablestates:By locking the write access, there is in effect only a single writer, and it is therefore unnecessary to lock reads.
Note that while this is true for
Hashtable, it is not the case forDictionary<TKey, TValue>.