Locking by string. Is this safe/sane?

前端 未结 9 1654
-上瘾入骨i
-上瘾入骨i 2020-12-14 01:33

I need to lock a section of code by string. Of course the following code is hideously unsafe:

lock(\"http://someurl\")
{
    //bla
}

So I\'

9条回答
  •  难免孤独
    2020-12-14 01:36

    You've created a pretty complex wrapper around a simple lock statement. Wouldn't it be better to create a dictionary of url's and create a lock object for each and everyone. You could simply do.

    objLink = GetUrl("Url"); //Returns static reference to url/lock combination
    lock(objLink.LockObject){
        //Code goes here
    }
    

    You could even simplify this by locking the objLink object directly wich could be the GetUrl("Url") string instance. (you'd have to lock the static list of strings though)

    You're original code if very error prone. If the code:

    if (obj.Return())
    {
    keyLocks.Remove(url);
    }
    

    If the original finally code throws an exception you're left with an invalid LockObject state.

提交回复
热议问题