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.
// Read the volatile field.if (_done)
}Dot Net Perls
Program info. Why is the bool volatile? First, the logic in this program is correct even without the volatile modifier on the bool.
Detail Compilers introduce extra, hidden complexity—they use a lot of optimizations.
And Some of these optimizations reorder loads and stores from variables. So conceptually the program could be incorrect.
Thus The order of assignments could change. When multiple threads execute at once, this can cause serious problems.
Detail Volatile tells the compiler not to change the order of accesses to the field.
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.
Performance. Can volatile fields cause a performance problem? In some cases, this may happen. It is probably a better idea not to use volatile in your programs at all.
A summary. Volatile restrict the optimizations the compiler makes regarding loads and stores into the field. This helps threaded programs.