Is locking access to a bool required or is it Overkill

前端 未结 3 1121
隐瞒了意图╮
隐瞒了意图╮ 2021-02-13 20:15

I have a class that is designed primarily as a POCO class, with various Threads and Tasks could read its values, and only others only occasionally updating these values. This se

3条回答
  •  误落风尘
    2021-02-13 20:43

    No type is truly safe! More precisely, the C# specifications assure you that reading or assignation of structure types less than 4 bytes or references are atomic. if your operating system is 64 bits, the CLR does a little better by assuring the same thing for structures less than 8 bytes.

    But anything more complicated than an assignation or a read of a value can potentially be interrupted by another competing thread if you are not careful.

    Even something as simple as this:

    myBool = !myBool
    

    can get an unexpected result if a competing thread modify the value of myBool.

    Use of locks is advised if you want to be sure something like that does not happen. Use of the volatile keyword is strongly discouraged unless you know exactly what your doing. Check these blog posts for additionnal information.

    However in your example where the property does not do anything else than a single write or a single read, locking is useless. But it would not be if there was any additionnal treatment.

提交回复
热议问题