volatile (Riferimenti per C#)

La parola chiave volatile indica che un campo potrebbe essere modificato da più thread in esecuzione contemporaneamente.I campi dichiarati volatile non sono soggetti a ottimizzazioni del compilatore che presuppongono l'accesso da un singolo thread.In questo modo nel campo è sempre presente il valore più aggiornato.

Il modificatore volatile è utilizzato in genere per un campo al quale accedono più thread senza ricorrere all'istruzione lock per la serializzazione dell'accesso.

La parola chiave volatile può essere applicata ai seguenti tipi di campi:

  • Tipi di riferimento.

  • Tipi puntatore in un contesto unsafe.Si noti che mentre il puntatore stesso può essere volatile, l'oggetto al quale punta non può esserlo.In altre parole, non è possibile dichiarare un "puntatore volatile".

  • Tipi quali sbyte, byte, short, ushort, int, uint, char, float e bool.

  • Il tipo enum con uno dei tipi di base seguenti: byte, sbyte, short, ushort, int o uint.

  • Parametri di tipo generico riconosciuti come tipi di riferimento.

  • IntPtr e UIntPtr.

La parola chiave volatile può essere applicata solo a campi di una classe o una struttura.Le variabili locali non possono essere dichiarate volatile.

Esempio

Nell'esempio riportato di seguito viene illustrato come dichiarare la variabile di un campo pubblico come volatile.

    class VolatileTest
    {
        public volatile int i;

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

Nell'esempio riportato di seguito viene illustrato come creare un thread ausiliario o di lavoro da utilizzare per eseguire l'elaborazione in parallelo con quella del thread primario.Per informazioni complementari sul multithreading, vedere Threading gestito e Threading (C# e 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.
}

Specifiche del linguaggio C#

Per ulteriori informazioni, vedere la Specifiche del linguaggio C#. La specifica del linguaggio è la fonte ufficiale per la sintassi e l'utilizzo di C#.

Vedere anche

Riferimenti

Parole chiave di C#

Modificatori (Riferimenti per C#)

Concetti

Guida per programmatori C#

Altre risorse

Riferimenti per C#