Получи случайную криптовалюту за регистрацию!

What is the volatile keyword used for? In C# volatile tells t | C# 1001 notes

What is the volatile keyword used for?

In C# volatile tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself (such as the operating system, the hardware, or a concurrently executing thread). The compiler will then avoid any optimisations that may result in problems if the variable changes "outside of its control".

Or in more simple terms:

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.