Simple Solution To Hashtables and Thread Safety

Shortly after I posted the original entry on this, I figured out a much more simple way than using version numbers, etc.

Item item = null;
bool lockWasSuccessful = false;

while(true) {
    lock(hashtable) {
        item = hashtable[key];
        lockWasSuccessful = Monitor.TryEntry(item);

    if(lockWasSuccessful == false) {

// If we reach here, the item was successfully locked

    try {

// Application code goes here

    finally {


So, the secret here is that I use TryEnter to try to lock the object while the hashtable is locked. I then drop the lock on the hashtable and check to see if the TryEnter worked. If it did not, I just repeat the process. If it did, then I’m free to go do application stuff, remembering to drop the lock when I finish. Tres simple!

Does that solution make sense? It is the simplest one I can think of that satisfies my performance requirements. Much more simple than the version number scheme I was using.

Any comments?

— bab


Now playing: [Dream Theater][1] – Six Degrees Of Inner Turbulence (Disc 2) – [VIII. Losing Time – Grand Finale][2]

[1]: Theater [2]: Losing Time - Grand Finale&artistTerm=Dream Theater