I need to lock a section of code by string. Of course the following code is hideously unsafe:
lock(\"http://someurl\")
{
//bla
}
So I\'
About 2 years ago i had to implement the same thing:
I'm trying to write an image cache where multiple clients (over a 100 or so) are likely to request the image simultaneously. The first hit will request the image from another server, and I'd like all other requests to the cache to block until this operation is complete so that they can retrieve the cached version.
I ended up with code doing pretty the same as yours (the dictionary of LockObjects). Well, yours seems to be better encapsulated.
So, I think you have quite a good solution. Just 2 comments:
If you need even better peformance it maybe useful to utilize some kind of ReadWriteLock, since you have 100 readers and only 1 writer getting the image from another server.
I am not sure what happens in case of thread switch just before Monitor.Enter(obj); in your LockOperation(). Say, the first thread wanting the image constructs a new lock and then thread switch just before it enters critical section. Then it could happen that the second thread enters the critical section before the first. Well could be that this is not a real problem.