lock为什么只能锁定引用不能锁定值类型

他要的就是引用类型,如果你传一个值类型,会装箱,下次代码运行到这里,又会装箱,两次不是同一个对象,所以锁不住


lock(x)
{
  ...
}

实际是通过Monitor对象完成的锁:

上面等同于:

System.Object obj = (System.Object)x;
System.Threading.Monitor.Enter(obj);
try
{
  ...  
}
finally
{
  System.Threading.Monitor.Exit(obj);
}

进而引用msdn原话:
Use Monitor to lockobjects (that is, reference types), not value types. When you pass avalue type variable to Enter, it is boxed as an object. If you pass thesame variable to Enter again, it is boxed as a separate object, and thethread does not block. In this case, the code that Monitor issupposedly protecting is not protected. Furthermore, when you pass thevariable to Exit, still another separate object is created. Because theobject passed to Exit is different from the object passed to Enter,Monitor throws SynchronizationLockException. For more information, seethe conceptual topic Monitors.


你可能感兴趣的:(C#)