When should the volatile keyword be used in C#?

前端 未结 10 851
盖世英雄少女心
盖世英雄少女心 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:32

    I found this article by Joydip Kanjilal very helpful!

    When you mark an object or a variable as volatile, it becomes a candidate for volatile reads and writes. It should be noted that in C# all memory writes are volatile irrespective of whether you are writing data to a volatile or a non-volatile object. However, the ambiguity happens when you are reading data. When you are reading data that is non-volatile, the executing thread may or may not always get the latest value. If the object is volatile, the thread always gets the most up-to-date value

    I'll just leave it here for reference

提交回复
热议问题