Hashtable.Clear thread-safety?

Q: Is it safe for a single writer to
call Hashtable.Clear() with multiple concurrent readers?o ns = "urn:schemas-microsoft-com:office:office" />

A: (from the developer that owns
Hashtable) It depends on what you want. Clear() will not cause a hashtable to be
inconsistent state, so hashtable will be not corrupted. The document says
Hashtable is thread-safe for a single writer and concurrent readers, but
unfortunately the current implementation doesn’t completely hold that up. The race condition happens when we copy
a hashtable bucket in reader and writer is reusing the same bucket. By reusing I mean the writer frees a
bucket and add a new item to the same bucket. Since a bucket contains hashcode,
key and value. We might copy the key from the old item and the value from the
new item. So in theory you can still hit this problem if you clear all the items
in a hashtable and then insert a new one, although you might never hit it in
practice.

Remove and Clear are the only
functions which will free a bucket. Value is written before keys in Add, but key
is set to null before value is set to null in Clear and Remove. So it is
possible your reader has copied a key in a bucket and then Writer kicks in and
changes the value to null. A more serious problem is that you can get a value
which belongs to another key. That will cause grief. Changing the order will not
solve the problem.

You
can use System.Threading.ReaderWriterLock to do the synchronization or use
Hashtable.Synchronized to get a synchronized wrapper