volatile 關鍵字指示一個欄位可以由多個同時執行的線程修改。聲明為 volatile 的欄位不受編譯器最佳化(假定由單個線程訪問)的限制。這樣可以確保該欄位在任何時間呈現的都是最新的值。
volatile 修飾符通常用於由多個線程訪問但不使用 lock 語句對訪問進行序列化的欄位。
volatile 關鍵字可應用於以下類型的欄位:
參考型別。
指標類型(在不安全的上下文中)。請注意,雖然指標本身可以是可變的,但是它指向的對象不能是可變的。換句話說,您無法聲明“指向可變對象的指標”。
類型,如 sbyte、byte、short、ushort、int、uint、char、float 和 bool。
具有以下基底類型之一的枚舉類型:byte、sbyte、short、ushort、int 或 uint。
已知為參考型別的泛型型別參數。
IntPtr 和 UIntPtr。
可變關鍵字僅可應用於類或結構欄位。不能將局部變數聲明為 volatile。
樣本
下面的樣本說明如何將公用欄位變數聲明為 volatile。
C#複製
class VolatileTest { public volatile int i; public void Test(int _i) { i = _i; } }
下面的樣本示範如何建立輔助線程,並用它與主線程並存執行處理。有關多執行緒的背景資訊,請參見託管線程處理和線程處理(C# 和 Visual Basic)。
C#複製
using System;using System.Threading;public class Worker{ // This method is called when the thread is started. public void DoWork() { while (!_shouldStop) { Console.WriteLine("Worker thread: working..."); } Console.WriteLine("Worker thread: terminating gracefully."); } public void RequestStop() { _shouldStop = true; } // Keyword volatile is used as a hint to the compiler that this data // member is accessed by multiple threads. private volatile bool _shouldStop;}public class WorkerThreadExample{ static void Main() { // Create the worker thread object. This does not start the thread. Worker workerObject = new Worker(); Thread workerThread = new Thread(workerObject.DoWork); // Start the worker thread. workerThread.Start(); Console.WriteLine("Main thread: starting worker thread..."); // Loop until the worker thread activates. while (!workerThread.IsAlive) ; // Put the main thread to sleep for 1 millisecond to // allow the worker thread to do some work. Thread.Sleep(1); // Request that the worker thread stop itself. workerObject.RequestStop(); // Use the Thread.Join method to block the current thread // until the object's thread terminates. workerThread.Join(); Console.WriteLine("Main thread: worker thread has terminated."); } // Sample output: // Main thread: starting worker thread... // Worker thread: working... // Worker thread: working... // Worker thread: working... // Worker thread: working... // Worker thread: working... // Worker thread: working... // Worker thread: terminating gracefully. // Main thread: worker thread has terminated.}