C#中的volatile關鍵字
阿新 • • 發佈:2018-01-27
ola 關鍵字 current ember oop doc test word sharp
volatile
關鍵字指示一個字段可以由多個同時執行的線程修改。 聲明為 volatile
的字段不受編譯器優化(假定由單個線程訪問)的限制。 這樣可以確保該字段在任何時間呈現的都是最新的值。
volatile
修飾符通常用於由多個線程訪問、但不使用 lock 語句對訪問進行序列化的字段。
volatile
關鍵字可應用於以下類型的字段:
-
引用類型。
-
指針類型(在不安全的上下文中)。 請註意,雖然指針本身可以是可變的,但是它指向的對象不能是可變的。 換句話說,不能聲明“指向可變對象的指針”。
-
類型,如 sbyte、byte、short、ushort、int、uint、char、float 和 bool。
-
具有以下基類型之一的枚舉類型:byte、sbyte、short、ushort、int 或 uint。
-
已知為引用類型的泛型類型參數。
-
IntPtr 和 UIntPtr。
可變關鍵字僅可應用於類或結構的字段。 不能將局部變量聲明為 volatile
。
示例
下面的示例說明如何將公共字段變量聲明為 volatile
。
class VolatileTest { public volatile int i; public void Test(int _i) { i = _i; } }
示例
下面的示例演示如何創建輔助線程,並用它與主線程並行執行處理。 有關多線程處理的背景信息,請參閱 線程和線程。
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. }
C#中的volatile關鍵字