Locking by string. Is this safe/sane?

前端 未结 9 1649
-上瘾入骨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:49

    Locking by an arbitrary string instance would be a bad idea, because Monitor.Lock locks the instance. If you had two different string instances with the same content, that would be two independent locks, which you don't want. So you're right to be concerned about arbitrary strings.

    However, .NET already has a built-in mechanism to return the "canonical instance" of a given string's content: String.Intern. If you pass it two different string instances with the same content, you will get back the same result instance both times.

    lock (string.Intern(url)) {
        ...
    }
    

    This is simpler; there's less code for you to test, because you'd be relying on what's already in the Framework (which, presumably, already works).

提交回复
热议问题