volatile (référence C#)

Le mot clé volatile indique qu'un champ peut être modifié par plusieurs threads qui s'exécutent simultanément. Les champs qui sont déclarés volatile ne sont pas soumis aux optimisations du compilateur qui supposent l'accès par un seul thread. Cela garantit que la valeur la plus à jour est présente dans le champ à tout moment.

Le modificateur volatile est généralement utilisé pour un champ auquel accèdent plusieurs threads sans utiliser l'instruction lock pour sérialiser l'accès.

Le mot clé volatile peut être appliqué aux champs des types suivants :

  • Types référence.

  • Types pointeur (dans un contexte unsafe). Notez que, même si le pointeur lui-même peut être volatile, l'objet sur lequel il pointe ne le peut pas. En d'autres termes, vous ne pouvez pas déclarer un pointeur vers un objet volatile.

  • Types tels que sbyte, byte, short, ushort, int, uint, char, float et bool.

  • Type enum avec l'un des types de base suivants : byte, sbyte, short, ushort, int, ou uint.

  • Paramètres de type générique connus comme des types référence.

  • IntPtr et UIntPtr.

Le mot clé volatile ne peut s'appliquer qu'aux champs d'une classe ou d'une structure. Les variables locales ne peuvent pas être déclarées volatile.

Exemple

L'exemple ci-dessous montre comment déclarer une variable de champ public comme volatile.

    class VolatileTest
    {
        public volatile int i;

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

L'exemple suivant montre comment il est possible de créer un thread auxiliaire ou de travail et de l'utiliser pour effectuer le traitement en parallèle avec le thread principal. Pour obtenir des informations générales sur le multithreading, consultez Threading managé et Threads (C# et 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.
}

Spécification du langage C#

Pour plus d'informations, voir la Spécification du langage C#. La spécification du langage est la source de référence pour la syntaxe C# et son utilisation.

Voir aussi

Référence

Mots clés C#

Modificateurs (référence C#)

Concepts

Guide de programmation C#

Autres ressources

Référence C#