Why can't we lock on a value type?

前端 未结 9 1081
天涯浪人
天涯浪人 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 06:42

    The following is taken from MSDN:

    The lock (C#) and SyncLock (Visual Basic) statements can be used to ensure that a block of code runs to completion without interruption by other threads. This is accomplished by obtaining a mutual-exclusion lock for a given object for the duration of the code block.

    and

    The argument provided to the lock keyword must be an object based on a reference type, and is used to define the scope of the lock.

    I would assume that this is in part because the lock mechanism uses an instance of that object to create the mutual exclusion lock.

提交回复
热议问题