C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Next: In the example, there are two static fields. One is an object reference of string type. The other is a volatile bool value type.
StaticStatic StringThen: In the Main method, a new thread is created, and the SetVolatile method is invoked. In SetVolatile, both the fields are set.
ThreadStartC# program that uses volatile field
using System;
using System.Threading;
class Program
{
static string _result;
static volatile bool _done;
static void SetVolatile()
{
// Set the string.
_result = "The Dev Codes";
// 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);
}
}
}
Output
The Dev Codes
And: Some of these optimizations reorder loads and stores from variables. So conceptually the program could be incorrect.
Notice: Thanks to Robert Paveza for writing in with a correction. It originally contained an incorrect statement.