C# Volatile Keyword
Of the many keywords in C#, volatile is one of the lesser known and last commonly used keywords. Today, I will in 5 minutes of less, explain what the volatile keyword is for and when the volatile keyword should be used. The aim is that you will click away from this website understanding the need for using volatile.
With the introduction of the System.Threading namespace, Multi-threading became incredibly easy. It was unfair on our predecessors really;
Thread backgroundThread = new Thread(new ThreadStart(MethodToRung)); backgroundThread.Start();
Consider the following example;
private bool _runIfTrue = true;
If _runIfTrue is being access from multiple threads, being read within a while loop from a secondary thread, but is updated on the main thread, there is a possibility that the value will not update within the secondary thread, and the loop will continue to operate. However, a simple alteration;
private volatile bool _runIfTrue = true;
Will ensure that the value is updated within the secondary thread, as the value is retrieved upon each access from the correct location.
So, how does that work?
The volatile keyword, which is now attached to the variable being read and written to from multiple threads, tells the compiler that this behaviour is expected here, and to not try and do anything about it. Volatile here is used by definition, the value of this field can change at any time, from anywhere, so you shouldn’t try and save a value for this. You see, when a secondary thread is initialized, the value stored within the local variable is passed to the thread, so if this started as true, true is passed over. The synchronisation isn’t always great, and this can mean the value stored in a secondary thread remains true, despite a different thread Changing this to false.
The volatile keyword should be used when a field is written to or read from more than a single thread, at any one given moment.
However, if you use a lock statement, the need for the volatile keyword becomes negate. This is because of the synchronisation between the threads offered by the lock statement.
By now, in less than 5 minutes of reading, you should understand the volatile keyword and when it should be used.