Sample code to illustrate a deadlock by using lock(this)

前端 未结 6 1186
我在风中等你
我在风中等你 2020-12-23 20:57

I\'ve read several articles and posts that say that lock(this), lock(typeof(MyType)), lock(\"a string\") are all bad practice because

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-23 21:40

    The idea is that you should never lock on something you cannot control who has access to.

    Type objects are singletons visible to every .net piece of code and you cannot control who locks on your "this" object from the outside.

    Same thing is for strings: since strings are immutable, the framework keeps just one instance of "hard coded" strings and puts them in a pool (the string is said to be interned), if you write two times in your code the string "hello", you will always get the same abject.

    Consider the following example: you wrote just Thread1 in your super private call, while Thread2 is called by some library you are using in a background thread...

    void Thread1()
    {
      lock (typeof(int))
      {
        Thread.Sleep(1000);
        lock (typeof(long))
          // do something
      }
    }
    
    void Thread2()
    {
      lock (typeof(long))
      {
        Thread.Sleep(1000);
        lock (typeof(int))
          // do something
      }
    }
    

提交回复
热议问题