This modifier reduces concurrency issues. Compilers reorder instructions in blocks. This improves performance but causes problems for concurrent threads.
Volatile provides a way to affect how the compiler optimizes accesses to a field. It can fix certain kinds of bugs in threaded programs.
This example would function correctly without the volatile modifier. It illustrates the concept of the volatile keyword, not to provide a real-world example.
static
fields. One is an object reference of string
type. The other is a volatile bool
value type.Main
method, a new thread is created, and the SetVolatile
method is invoked. In SetVolatile
, both the fields are set.using System; using System.Threading; class Program { static string _result; static volatile bool _done; static void SetVolatile() { // Set the string. _result = "Dot Net Perls"; // The volatile field must be set at the end of this method. _done = true; } static void Main() { // Run the above method on a new thread. new Thread(new ThreadStart(SetVolatile)).Start(); // Wait a while. Thread.Sleep(200); // Read the volatile field. if (_done) { Console.WriteLine(_result); } } }Dot Net Perls
Program
infoWhy is the bool
volatile? First, the logic in this program is correct even without the volatile modifier on the bool
.
Flags
The example demonstrates a volatile field used as a flag. The bool
type is commonly used as a flag. So when the flag is set to true, you can take other action on that variable.
Volatile restrict the optimizations the compiler makes regarding loads and stores into the field. This helps threaded programs.