ใช้ volatile keyword เพื่อลดปัญหา Concurrency (Race Conditions) ใน C#
ตัวอย่าง: Volatile Field
class Program
{
public volatile int a;
public void Program(int _a) { a = _a; }
}
ตัวอย่าง: ใช้กับ Static Variables และ Thread
static string _out;
static volatile bool _new;
void volatileFunc()
{
_out = "Welcome!";
_new = true;
}
// รันบน Thread
new Thread(new ThreadStart(volatileFunc)).Start();
// อ่านค่า Volatile Variable
if (_new)
{
Console.WriteLine(_out);
}
volatile บอก Compiler อย่างไม่ให้ Optimize การเข้าถึงตัวแปรนี้ ให้อ่าน/เขียนจาก Main Memory เสมอ