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][1] – Six Degrees Of Inner Turbulence (Disc 2) – [VIII. Losing Time – Grand Finale][2]
[1]: http://phobos.apple.com/WebObjects/MZSearch.woa/wa/advancedSearchResults?artistTerm=Dream Theater [2]: http://phobos.apple.com/WebObjects/MZSearch.woa/wa/advancedSearchResults?songTerm=VIII. Losing Time - Grand Finale&artistTerm=Dream Theater