Brian Button - One Agile Coder

Blogging on all things .Net, C#, and Agile

<November 2008>
SuMoTuWeThFrSa
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456


Navigation

Enterprise Library V1 Team

Blogs I read

Agile Solutions Group

Subscriptions



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) {
        Thread.Sleep(0);
        continue;
    }

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

    try {

// Application code goes here

    }
    finally {
        Monitor.Exit(item);
    }

    break;
}

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 - Six Degrees Of Inner Turbulence (Disc 2) - VIII. Losing Time - Grand Finale

posted on Friday, September 17, 2004 10:13 AM by brianbuttonxp





Powered by Dot Net Junkies, by Telligent Systems