I am trying to understand the usage of volatile keyword, so I have written a small example where I was thinking to use Volatile keyword, but currently I am getting the same behavior either I use Volatile keyword or I don't use it.
Following is the code which I am running and I expected the Thread t2 keep executing, even if t1 was updating the ExitLoop property
namespace UsageOfVolatileKeyword
{
class Program
{
static void Main()
{
Test t = new Test();
Thread t2 = new Thread(() => { while (!t.ExitLoop) { Console.WriteLine("In loop"); } });
t2.Start();
Thread t1 = new Thread(() => t.ExitLoop = true);
t1.Start();
t2.Join();
Console.WriteLine("I am done");
Console.ReadLine();
}
}
class Test
{
private bool _exitLoop = false; //I am marking this variable as volatile.
public bool ExitLoop
{
get { return _exitLoop; }
set { _exitLoop = value; }
}
}
}
It will be nice if somebody can help me understand what wrong I am doing and what's the proper usage of Volatile keyword is.