When should the volatile keyword be used in C#?

前端 未结 10 1041
盖世英雄少女心
盖世英雄少女心 2020-11-22 12:04

Can anyone provide a good explanation of the volatile keyword in C#? Which problems does it solve and which it doesn\'t? In which cases will it save me the use of locking?

10条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 12:38

    Sometimes, the compiler will optimize a field and use a register to store it. If thread 1 does a write to the field and another thread accesses it, since the update was stored in a register (and not memory), the 2nd thread would get stale data.

    You can think of the volatile keyword as saying to the compiler "I want you to store this value in memory". This guarantees that the 2nd thread retrieves the latest value.

提交回复
热议问题