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.
But 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.
Instead 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 17, 2022 (simplify).