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

前端 未结 6 1170
我在风中等你
我在风中等你 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:37

    A deadlock will only occur if you have more than one lock. You need a situation where both threads hold a resource that the other needs (which means there has to be a least two resources, and the two threads have to attempt to acquire them in a different order)

    So a simple example:

    // thread 1
    lock(typeof(int)) {
      Thread.Sleep(1000);
      lock(typeof(float)) {
        Console.WriteLine("Thread 1 got both locks");
      }
    
    }
    
    // thread 2
    lock(typeof(float)) {
      Thread.Sleep(1000);
      lock(typeof(int)) {
        Console.WriteLine("Thread 2 got both locks");
      }
    }
    

    Assuming both threads are started within a second of each others, they will both have time to grab the first lock before anyone gets to the inner lock. Without the Sleep() call, one of the threads would most likely have time to get and release both locks before the other thread even got started.

提交回复
热议问题