What is the volatile keyword purpose in c#?

c#, multithreading

Solution

The `volatile` keyword tells the compiler that a variable can change at any time, so it shouldn't optimise away reading and writing of the variable.

Consider code like this:

int sum;
for (var i = 0; i < 1000; i++) {
  sum += x * i;
}

As the variable `x` doesn't change inside the loop, the compiler might read the variable once outside the loop and just use the same value throughout the loop.

If you make the variable `x` volatile, the compiler will read the value of the variable each time that it is used, so if you change the value in a different thread, the new value will be used immediately.

Problem

I want to see the real time use of `Volatile` keyword in c#. but am unable to project the best example. the below sample code works without `Volatile` keyword how can it possible? ``` class Program { private static int a = 0, b = 0; static void Main(string[] args) { Thread t1 = new Thread(Method1); Thread t2 = new Thread(Method2); t1.Start(); t2.Start(); Console.ReadLine(); } static void Method1() { a = 5; b = 1; } static void Method2() { if (b == 1) Console.WriteLine(a); } } ``` In the above code i am getting a value as 5. how it works without using volatile keyword?

Original source