Why can't we lock on a value type?

前端 未结 9 1099
天涯浪人
天涯浪人 2020-12-08 06:27

I was trying to lock a Boolean variable when I encountered the following error :

\'bool\' is not a reference type as require

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 06:52

    It expands to:

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

    Although they would compile, Monitor.Enter/Exit require a reference type because a value type would be boxed to a different object instance each time so each call to Enter and Exit would be operating on different objects.

    From the MSDN Enter method page:

    Use Monitor to lock objects (that is, reference types), not value types. When you pass a value type variable to Enter, it is boxed as an object. If you pass the same variable to Enter again, it is boxed as a separate object, and the thread does not block. In this case, the code that Monitor is supposedly protecting is not protected. Furthermore, when you pass the variable to Exit, still another separate object is created. Because the object passed to Exit is different from the object passed to Enter, Monitor throws SynchronizationLockException. For more information, see the conceptual topic Monitors.

提交回复
热议问题