Do properties have volatile effect?

后端 未结 6 1802
無奈伤痛
無奈伤痛 2021-02-19 10:54

In the code below will read1 be always equal to read2, provided property Flag can be changed from other threads? Concern here is that

6条回答
  •  别跟我提以往
    2021-02-19 11:17

    Yes it can be changed naturally.

    Even in the code provided it's not guranteed that read1 would be equal to read2.

    Considering that meanwhile /* some more code */ executed, Flag can be affected by other threads.

    EDIT

    The equality of read1 and read2 has nothing to do with inlining or not, Flag is a bool, so it's a value type. So

    • var read1 = Flag; //let's say read1 TRUE
    • Flag = False
    • var read2 = Flag; //read2 is FALSE, but read1 remains TRUE

    This is valid in non multithreaded environment too, cause you operating on value type.

    If this is not what you're asking for, please clarify.

提交回复
热议问题