volatile (C# 參考)

volatile 關鍵字表示同時執行的多執行緒可能修改了欄位。 宣告為 volatile 的欄位不遵從假設單一執行緒存取的編譯器最佳化。 這確保最新的值會一直出現在欄位中。

由多個執行緒在未以 lock 陳述式 (Statement) 將存取動作序列化的情況下所存取的欄位上,經常會使用 volatile 修飾詞 (Modifier)。

volatile 關鍵字可套用至以下型別的欄位:

  • 參考型別。

  • 指標型別 (在 unsafe 內容中)。 請注意,即使指標本身可以為 Volatile,但所指向的物件不可為 Volatile。 換句話說,您不能宣告 Volatile 的指標。

  • sbyte、byte、short、ushort、int、uint、char、float 和 bool 之類的型別。

  • 具有下列一種基底型別的列舉型別:byte、sbyte、short、ushort、int 或 uint。

  • 已知為參考型別的泛用型別參數。

  • IntPtrUIntPtr

Volatile 關鍵字只能套用至類別或結構 (Struct) 的欄位。 區域變數無法宣告為 volatile。

範例

下列範例將示範如何將公用欄位變數宣告為 volatile。

    class VolatileTest
    {
        public volatile int i;

        public void Test(int _i)
        {
            i = _i;
        }
    }

下列範例會示範如何建立輔助執行緒或背景工作執行緒,以及使用它們和主要執行緒執行平行的處理過程。 如需多執行緒處理的背景資訊,請參閱 Managed 執行緒處理執行緒 (C# 和 Visual Basic)

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# 語言規格

如需詳細資訊,請參閱 C# 語言規格。 語言規格是 C# 語法和用法的決定性來源。

請參閱

參考

C# 關鍵字

修飾詞 (C# 參考)

概念

C# 程式設計手冊

其他資源

C# 參考