Why can't we lock on a value type?

前端 未结 9 1083
天涯浪人
天涯浪人 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 07:05

    According to this MSDN Thread, the changes to a reference variable may not be visible to all the threads and they might end up using stale values, and AFAIK I think value types do make a copy when they are passed between threads.

    To quote exactly from MSDN

    It's also important to clarify that the fact the assignment is atomic does not imply that the write is immediately observed by other threads. If the reference is not volatile, then it's possible for another thread to read a stale value from the reference some time after your thread has updated it. However, the update itself is guaranteed to be atomic (you won't see a part of the underlying pointer getting updated).

提交回复
热议问题