volatile(C# 參考)


volatile(C# 參考)

 

若要了解有關 Visual Studio 2017 RC 的最新文檔,請參閱 Visual Studio 2017 RC 文檔

volatile 關鍵字指示一個字段可以由多個同時執行的線程修改。 聲明為 volatile 的字段不受編譯器優化(假定由單個線程訪問)的限制。 這樣可以確保該字段在任何時間呈現的都是最新的值。

volatile 修飾符通常用於由多個線程訪問但不使用 lock 語句對訪問進行序列化的字段。

volatile 關鍵字可應用於以下類型的字段:

  • 引用類型。

  • 指針類型(在不安全的上下文中)。 請注意,雖然指針本身可以是可變的,但是它指向的對象不能是可變的。 換句話說,您無法聲明“指向可變對象的指針”。

  • 類型,如 sbyte、byte、short、ushort、int、uint、char、float 和 bool。

  • 具有以下基類型之一的枚舉類型:byte、sbyte、short、ushort、int 或 uint。

  • 已知為引用類型的泛型類型參數。

  • IntPtrUIntPtr

可變關鍵字僅可應用於類或結構字段。 不能將局部變量聲明為 volatile

示例
 

 

下面的示例說明如何將公共字段變量聲明為 volatile

 

C#
    class VolatileTest
    {
        public volatile int i;

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

 

示例
 

 

下面的示例演示如何創建輔助線程,並用它與主線程並行執行處理。 有關多線程處理的背景信息,請參見Threading線程

 

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.
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM