Interlocked.CompareExchange Méthode

Définition

Compare deux valeurs et remplace la première valeur en cas d'égalité.

Surcharges

CompareExchange(UIntPtr, UIntPtr, UIntPtr)

Compare deux handles ou pointeurs spécifiques à la plateforme et remplace le premier en cas d’égalité.

CompareExchange(UInt64, UInt64, UInt64)

Compare deux entiers 64 bits non signés, et remplace la première valeur en cas d’égalité.

CompareExchange(UInt32, UInt32, UInt32)

Compare deux entiers 32 bits non signés, et remplace la première valeur en cas d’égalité.

CompareExchange(UInt16, UInt16, UInt16)
CompareExchange(Single, Single, Single)

Compare deux nombres à virgule flottante simple précision et remplace le premier en cas d'égalité.

CompareExchange(Object, Object, Object)

Compare deux objets et remplace le premier en cas d’égalité des références.

CompareExchange(SByte, SByte, SByte)
CompareExchange(Int64, Int64, Int64)

Compare deux entiers signés de 64 bits et remplace la première valeur en cas d'égalité.

CompareExchange(Int32, Int32, Int32)

Compare deux entiers signés de 32 bits et remplace la première valeur en cas d'égalité.

CompareExchange(Int16, Int16, Int16)
CompareExchange(Double, Double, Double)

Compare deux nombres à virgule flottante double précision et remplace le premier en cas d'égalité.

CompareExchange(Byte, Byte, Byte)
CompareExchange(IntPtr, IntPtr, IntPtr)

Compare deux handles ou pointeurs spécifiques à la plateforme et remplace le premier en cas d’égalité.

CompareExchange<T>(T, T, T)

Compare deux instances du type référence spécifié T pour et remplace la première en cas d’égalité par référence.

CompareExchange(UIntPtr, UIntPtr, UIntPtr)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs

Important

Cette API n’est pas conforme CLS.

Compare deux handles ou pointeurs spécifiques à la plateforme et remplace le premier en cas d’égalité.

public:
 static UIntPtr CompareExchange(UIntPtr % location1, UIntPtr value, UIntPtr comparand);
[System.CLSCompliant(false)]
public static UIntPtr CompareExchange (ref UIntPtr location1, UIntPtr value, UIntPtr comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : unativeint * unativeint * unativeint -> unativeint
Public Shared Function CompareExchange (ByRef location1 As UIntPtr, value As UIntPtr, comparand As UIntPtr) As UIntPtr

Paramètres

location1
UIntPtr

unativeint

Destination UIntPtr, dont la valeur est comparée à celle de comparand et qui peut être remplacée par value.

value
UIntPtr

unativeint

Valeur UIntPtr qui remplace la valeur de destination si la comparaison conclut à une égalité.

comparand
UIntPtr

unativeint

Valeur UIntPtr comparée à celle de location1.

Retours

UIntPtr

unativeint

Valeur d’origine dans location1.

Attributs

Exceptions

L’adresse de location1 est un pointeur null.

S’applique à

CompareExchange(UInt64, UInt64, UInt64)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs

Important

Cette API n’est pas conforme CLS.

Compare deux entiers 64 bits non signés, et remplace la première valeur en cas d’égalité.

public:
 static System::UInt64 CompareExchange(System::UInt64 % location1, System::UInt64 value, System::UInt64 comparand);
[System.CLSCompliant(false)]
public static ulong CompareExchange (ref ulong location1, ulong value, ulong comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : uint64 * uint64 * uint64 -> uint64
Public Shared Function CompareExchange (ByRef location1 As ULong, value As ULong, comparand As ULong) As ULong

Paramètres

location1
UInt64

Destination, dont la valeur est comparée avec comparand et qui peut être remplacée.

value
UInt64

Valeur qui remplace la valeur de destination si la comparaison conclut à une égalité.

comparand
UInt64

Valeur comparée à celle de location1.

Retours

Valeur d’origine dans location1.

Attributs

Exceptions

L’adresse de location1 est un pointeur null.

S’applique à

CompareExchange(UInt32, UInt32, UInt32)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs

Important

Cette API n’est pas conforme CLS.

Compare deux entiers 32 bits non signés, et remplace la première valeur en cas d’égalité.

public:
 static System::UInt32 CompareExchange(System::UInt32 % location1, System::UInt32 value, System::UInt32 comparand);
[System.CLSCompliant(false)]
public static uint CompareExchange (ref uint location1, uint value, uint comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : uint32 * uint32 * uint32 -> uint32
Public Shared Function CompareExchange (ByRef location1 As UInteger, value As UInteger, comparand As UInteger) As UInteger

Paramètres

location1
UInt32

Destination, dont la valeur est comparée avec comparand et qui peut être remplacée.

value
UInt32

Valeur qui remplace la valeur de destination si la comparaison conclut à une égalité.

comparand
UInt32

Valeur comparée à celle de location1.

Retours

Valeur d’origine dans location1.

Attributs

Exceptions

L’adresse de location1 est un pointeur null.

S’applique à

CompareExchange(UInt16, UInt16, UInt16)

Important

Cette API n’est pas conforme CLS.

public:
 static System::UInt16 CompareExchange(System::UInt16 % location1, System::UInt16 value, System::UInt16 comparand);
[System.CLSCompliant(false)]
public static ushort CompareExchange (ref ushort location1, ushort value, ushort comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : uint16 * uint16 * uint16 -> uint16
Public Shared Function CompareExchange (ByRef location1 As UShort, value As UShort, comparand As UShort) As UShort

Paramètres

location1
UInt16
value
UInt16
comparand
UInt16

Retours

Attributs

S’applique à

CompareExchange(Single, Single, Single)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs

Compare deux nombres à virgule flottante simple précision et remplace le premier en cas d'égalité.

public:
 static float CompareExchange(float % location1, float value, float comparand);
public static float CompareExchange (ref float location1, float value, float comparand);
static member CompareExchange : single * single * single -> single
Public Shared Function CompareExchange (ByRef location1 As Single, value As Single, comparand As Single) As Single

Paramètres

location1
Single

Destination, dont la valeur est comparée avec comparand et qui peut être remplacée.

value
Single

Valeur qui remplace la valeur de destination si la comparaison conclut à une égalité.

comparand
Single

Valeur comparée à celle de location1.

Retours

Valeur d’origine dans location1.

Exceptions

L’adresse de location1 est un pointeur null.

Exemples

L’exemple de code suivant illustre une méthode thread-safe qui accumule un total de valeurs en cours d’exécution Single . Deux threads ajoutent une série de valeurs à l’aide de Single la méthode thread-safe et de l’ajout ordinaire, et une fois les threads terminés, les totaux sont comparés. Sur un ordinateur à double processeur, il existe une différence significative dans les totaux.

Dans la méthode thread-safe, la valeur initiale du total en cours d’exécution est enregistrée, puis la CompareExchange méthode est utilisée pour échanger le total nouvellement calculé avec l’ancien total. Si la valeur de retour n’est pas égale à la valeur enregistrée du total en cours d’exécution, un autre thread a mis à jour le total entre-temps. Dans ce cas, la tentative de mise à jour du total en cours d’exécution doit être répétée.

// This example demonstrates a thread-safe method that adds to a
// running total.  
using System;
using System.Threading;

public class ThreadSafe
{
    // Field totalValue contains a running total that can be updated
    // by multiple threads. It must be protected from unsynchronized 
    // access.
    private float totalValue = 0.0F;

    // The Total property returns the running total.
    public float Total { get { return totalValue; }}

    // AddToTotal safely adds a value to the running total.
    public float AddToTotal(float addend)
    {
        float initialValue, computedValue;
        do
        {
            // Save the current running total in a local variable.
            initialValue = totalValue;

            // Add the new value to the running total.
            computedValue = initialValue + addend;

            // CompareExchange compares totalValue to initialValue. If
            // they are not equal, then another thread has updated the
            // running total since this loop started. CompareExchange
            // does not update totalValue. CompareExchange returns the
            // contents of totalValue, which do not equal initialValue,
            // so the loop executes again.
        }
        while (initialValue != Interlocked.CompareExchange(ref totalValue, 
            computedValue, initialValue));
        // If no other thread updated the running total, then 
        // totalValue and initialValue are equal when CompareExchange
        // compares them, and computedValue is stored in totalValue.
        // CompareExchange returns the value that was in totalValue
        // before the update, which is equal to initialValue, so the 
        // loop ends.

        // The function returns computedValue, not totalValue, because
        // totalValue could be changed by another thread between
        // the time the loop ends and the function returns.
        return computedValue;
    }
}

public class Test
{
    // Create an instance of the ThreadSafe class to test.
    private static ThreadSafe ts = new ThreadSafe();
    private static float control;

    private static Random r = new Random();
    private static ManualResetEvent mre = new ManualResetEvent(false);

    public static void Main()
    {
        // Create two threads, name them, and start them. The
        // thread will block on mre.
        Thread t1 = new Thread(TestThread);
        t1.Name = "Thread 1";
        t1.Start();
        Thread t2 = new Thread(TestThread);
        t2.Name = "Thread 2";
        t2.Start();

        // Now let the threads begin adding random numbers to 
        // the total.
        mre.Set();
        
        // Wait until all the threads are done.
        t1.Join();
        t2.Join();

        Console.WriteLine("Thread safe: {0}  Ordinary float: {1}", 
            ts.Total, control);
    }

    private static void TestThread()
    {
        // Wait until the signal.
        mre.WaitOne();

        for(int i = 1; i <= 1000000; i++)
        {
            // Add to the running total in the ThreadSafe instance, and
            // to an ordinary float.
            //
            float testValue = (float) r.NextDouble();
            control += testValue;
            ts.AddToTotal(testValue);
        }
    }
}

/* On a dual-processor computer, this code example produces output 
   similar to the following:

Thread safe: 17039.57  Ordinary float: 15706.44
 */
' This example demonstrates a thread-safe method that adds to a
' running total.  
Imports System.Threading

Public Class ThreadSafe
    ' Field totalValue contains a running total that can be updated
    ' by multiple threads. It must be protected from unsynchronized 
    ' access.
    Private totalValue As Single = 0.0

    ' The Total property returns the running total.
    Public ReadOnly Property Total As Single
        Get
            Return totalValue
        End Get
    End Property

    ' AddToTotal safely adds a value to the running total.
    Public Function AddToTotal(ByVal addend As Single) As Single
        Dim initialValue, computedValue As Single
        Do
            ' Save the current running total in a local variable.
            initialValue = totalValue

            ' Add the new value to the running total.
            computedValue = initialValue + addend

            ' CompareExchange compares totalValue to initialValue. If
            ' they are not equal, then another thread has updated the
            ' running total since this loop started. CompareExchange
            ' does not update totalValue. CompareExchange returns the
            ' contents of totalValue, which do not equal initialValue,
            ' so the loop executes again.
        Loop While initialValue <> Interlocked.CompareExchange( _
            totalValue, computedValue, initialValue)
        ' If no other thread updated the running total, then 
        ' totalValue and initialValue are equal when CompareExchange
        ' compares them, and computedValue is stored in totalValue.
        ' CompareExchange returns the value that was in totalValue
        ' before the update, which is equal to initialValue, so the 
        ' loop ends.

        ' The function returns computedValue, not totalValue, because
        ' totalValue could be changed by another thread between
        ' the time the loop ends and the function returns.
        Return computedValue
    End Function
End Class

Public Class Test
    ' Create an instance of the ThreadSafe class to test.
    Private Shared ts As New ThreadSafe()
    Private Shared control As Single

    Private Shared r As New Random()
    Private Shared mre As New ManualResetEvent(false)

    <MTAThread> _
    Public Shared Sub Main()
        ' Create two threads, name them, and start them. The
        ' threads will block on mre.
        Dim t1 As New Thread(AddressOf TestThread)
        t1.Name = "Thread 1"
        t1.Start()
        Dim t2 As New Thread(AddressOf TestThread)
        t2.Name = "Thread 2"
        t2.Start()

        ' Now let the threads begin adding random numbers to 
        ' the total.
        mre.Set()
        
        ' Wait until all the threads are done.
        t1.Join()
        t2.Join()

        Console.WriteLine("Thread safe: {0}  Ordinary Single: {1}", ts.Total, control)
    End Sub

    Private Shared Sub TestThread()
        ' Wait until the signal.
        mre.WaitOne()

        For i As Integer = 1 to 1000000
            ' Add to the running total in the ThreadSafe instance, and
            ' to an ordinary Single.
            '
            Dim testValue As Single = r.NextDouble()
            control += testValue
            ts.AddToTotal(testValue)
        Next
    End Sub
End Class

' On a dual-processor computer, this code example produces output 
' similar to the following:
'
'Thread safe: 17039.57  Ordinary Single: 15706.44

Remarques

Si comparand et la valeur dans location1 sont égales, est value stocké dans location1. Dans le cas contraire, aucune opération n'est effectuée. Les opérations de comparaison et d’échange sont effectuées en tant qu’opération atomique. La valeur de retour de CompareExchange est la valeur d’origine dans location1, que l’échange ait lieu ou non.

Voir aussi

S’applique à

CompareExchange(Object, Object, Object)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.CoreCLR.cs

Compare deux objets et remplace le premier en cas d’égalité des références.

public:
 static System::Object ^ CompareExchange(System::Object ^ % location1, System::Object ^ value, System::Object ^ comparand);
public static object CompareExchange (ref object location1, object value, object comparand);
public static object? CompareExchange (ref object? location1, object? value, object? comparand);
static member CompareExchange : obj * obj * obj -> obj
Public Shared Function CompareExchange (ByRef location1 As Object, value As Object, comparand As Object) As Object

Paramètres

location1
Object

Objet de destination comparé par référence à comparand et qui peut être remplacé.

value
Object

Objet qui remplace l'objet de destination si la comparaison par référence conclut à une égalité.

comparand
Object

Objet qui est comparé par référence à l’objet se trouvant à l’emplacement location1.

Retours

Valeur d’origine dans location1.

Exceptions

L’adresse de location1 est un pointeur null.

Remarques

Important

À compter de .NET Framework 2.0, la surcharge de méthode CompareExchange<T>(T, T, T) fournit une alternative de type sécurisé pour les types référence. Nous vous recommandons de l’appeler au lieu de cette surcharge.

Si comparand et l’objet dans location1 sont égaux par référence, il value est stocké dans location1. Dans le cas contraire, aucune opération n'est effectuée. Les opérations de comparaison et d’échange sont effectuées en tant qu’opération atomique. La valeur de retour de CompareExchange est la valeur d’origine dans location1, que l’échange ait lieu ou non.

Notes

Les objets sont comparés pour l’égalité de référence plutôt que pour l’égalité de valeur. Par conséquent, deux instances boxées du même type de valeur (par exemple, l’entier 3) semblent toujours inégales et aucune opération n’est effectuée. N’utilisez pas cette surcharge avec les types valeur.

Voir aussi

S’applique à

CompareExchange(SByte, SByte, SByte)

Important

Cette API n’est pas conforme CLS.

public:
 static System::SByte CompareExchange(System::SByte % location1, System::SByte value, System::SByte comparand);
[System.CLSCompliant(false)]
public static sbyte CompareExchange (ref sbyte location1, sbyte value, sbyte comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : sbyte * sbyte * sbyte -> sbyte
Public Shared Function CompareExchange (ByRef location1 As SByte, value As SByte, comparand As SByte) As SByte

Paramètres

location1
SByte
value
SByte
comparand
SByte

Retours

Attributs

S’applique à

CompareExchange(Int64, Int64, Int64)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.CoreCLR.cs

Compare deux entiers signés de 64 bits et remplace la première valeur en cas d'égalité.

public:
 static long CompareExchange(long % location1, long value, long comparand);
public static long CompareExchange (ref long location1, long value, long comparand);
static member CompareExchange : int64 * int64 * int64 -> int64
Public Shared Function CompareExchange (ByRef location1 As Long, value As Long, comparand As Long) As Long

Paramètres

location1
Int64

Destination, dont la valeur est comparée avec comparand et qui peut être remplacée.

value
Int64

Valeur qui remplace la valeur de destination si la comparaison conclut à une égalité.

comparand
Int64

Valeur comparée à celle de location1.

Retours

Valeur d’origine dans location1.

Exceptions

L’adresse de location1 est un pointeur null.

Remarques

Si comparand et la valeur dans location1 sont égales, est value stocké dans location1. Dans le cas contraire, aucune opération n'est effectuée. Les opérations de comparaison et d’échange sont effectuées en tant qu’opération atomique. La valeur de retour de CompareExchange est la valeur d’origine dans location1, que l’échange ait lieu ou non.

Voir aussi

S’applique à

CompareExchange(Int32, Int32, Int32)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.CoreCLR.cs

Compare deux entiers signés de 32 bits et remplace la première valeur en cas d'égalité.

public:
 static int CompareExchange(int % location1, int value, int comparand);
public static int CompareExchange (ref int location1, int value, int comparand);
static member CompareExchange : int * int * int -> int
Public Shared Function CompareExchange (ByRef location1 As Integer, value As Integer, comparand As Integer) As Integer

Paramètres

location1
Int32

Destination, dont la valeur est comparée avec comparand et qui peut être remplacée.

value
Int32

Valeur qui remplace la valeur de destination si la comparaison conclut à une égalité.

comparand
Int32

Valeur comparée à celle de location1.

Retours

Valeur d’origine dans location1.

Exceptions

L’adresse de location1 est un pointeur null.

Exemples

L’exemple de code suivant illustre une méthode thread-safe qui accumule un total d’exécution. La valeur initiale du total en cours d’exécution est enregistrée, puis la CompareExchange méthode est utilisée pour échanger le total nouvellement calculé avec l’ancien total. Si la valeur de retour n’est pas égale à la valeur enregistrée du total en cours d’exécution, un autre thread a mis à jour le total entre-temps. Dans ce cas, la tentative de mise à jour du total en cours d’exécution doit être répétée.

Notes

La Add méthode, introduite dans la version 2.0 du .NET Framework, offre un moyen plus pratique d’accumuler des totaux d’exécution thread-safe pour les entiers.

// This example demonstrates a thread-safe method that adds to a
// running total.  It cannot be run directly.  You can compile it
// as a library, or add the class to a project.
#using <system.dll>

using namespace System::Threading;
public ref class ThreadSafe
{
private:

   // totalValue contains a running total that can be updated
   // by multiple threads. It must be protected from unsynchronized 
   // access.
   int totalValue;

public:

   property int Total 
   {

      // The Total property returns the running total.
      int get()
      {
         return totalValue;
      }

   }

   // AddToTotal safely adds a value to the running total.
   int AddToTotal( int addend )
   {
      int initialValue;
      int computedValue;
      do
      {
         
         // Save the current running total in a local variable.
         initialValue = totalValue;
         
         // Add the new value to the running total.
         computedValue = initialValue + addend;
         
         // CompareExchange compares totalValue to initialValue. If
         // they are not equal, then another thread has updated the
         // running total since this loop started. CompareExchange
         // does not update totalValue. CompareExchange returns the
         // contents of totalValue, which do not equal initialValue,
         // so the loop executes again.
      }
      while ( initialValue != Interlocked::CompareExchange( totalValue, computedValue, initialValue ) );

      
      // If no other thread updated the running total, then 
      // totalValue and initialValue are equal when CompareExchange
      // compares them, and computedValue is stored in totalValue.
      // CompareExchange returns the value that was in totalValue
      // before the update, which is equal to initialValue, so the 
      // loop ends.
      // The function returns computedValue, not totalValue, because
      // totalValue could be changed by another thread between
      // the time the loop ends and the function returns.
      return computedValue;
   }

};
// This example demonstrates a thread-safe method that adds to a
// running total.  It cannot be run directly.  You can compile it
// as a library, or add the class to a project.
using System.Threading;

public class ThreadSafe {
    // totalValue contains a running total that can be updated
    // by multiple threads. It must be protected from unsynchronized 
    // access.
    private int totalValue = 0;

    // The Total property returns the running total.
    public int Total {
        get { return totalValue; }
    }

    // AddToTotal safely adds a value to the running total.
    public int AddToTotal(int addend) {
        int initialValue, computedValue;
        do {
            // Save the current running total in a local variable.
            initialValue = totalValue;

            // Add the new value to the running total.
            computedValue = initialValue + addend;

            // CompareExchange compares totalValue to initialValue. If
            // they are not equal, then another thread has updated the
            // running total since this loop started. CompareExchange
            // does not update totalValue. CompareExchange returns the
            // contents of totalValue, which do not equal initialValue,
            // so the loop executes again.
        } while (initialValue != Interlocked.CompareExchange(
            ref totalValue, computedValue, initialValue));
        // If no other thread updated the running total, then 
        // totalValue and initialValue are equal when CompareExchange
        // compares them, and computedValue is stored in totalValue.
        // CompareExchange returns the value that was in totalValue
        // before the update, which is equal to initialValue, so the 
        // loop ends.

        // The function returns computedValue, not totalValue, because
        // totalValue could be changed by another thread between
        // the time the loop ends and the function returns.
        return computedValue;
    }
}
' This example demonstrates a thread-safe method that adds to a
' running total.  It cannot be run directly.  You can compile it
' as a library, or add the class to a project.
Imports System.Threading

Public Class ThreadSafe
    ' Field totalValue contains a running total that can be updated
    ' by multiple threads. It must be protected from unsynchronized 
    ' access.
    Private totalValue As Integer = 0

    ' The Total property returns the running total.
    Public ReadOnly Property Total As Integer
        Get
            Return totalValue
        End Get
    End Property

    ' AddToTotal safely adds a value to the running total.
    Public Function AddToTotal(ByVal addend As Integer) As Integer
        Dim initialValue, computedValue As Integer
        Do
            ' Save the current running total in a local variable.
            initialValue = totalValue

            ' Add the new value to the running total.
            computedValue = initialValue + addend

            ' CompareExchange compares totalValue to initialValue. If
            ' they are not equal, then another thread has updated the
            ' running total since this loop started. CompareExchange
            ' does not update totalValue. CompareExchange returns the
            ' contents of totalValue, which do not equal initialValue,
            ' so the loop executes again.
        Loop While initialValue <> Interlocked.CompareExchange( _
            totalValue, computedValue, initialValue)
        ' If no other thread updated the running total, then 
        ' totalValue and initialValue are equal when CompareExchange
        ' compares them, and computedValue is stored in totalValue.
        ' CompareExchange returns the value that was in totalValue
        ' before the update, which is equal to initialValue, so the 
        ' loop ends.

        ' The function returns computedValue, not totalValue, because
        ' totalValue could be changed by another thread between
        ' the time the loop ends and the function returns.
        Return computedValue
    End Function
End Class

Remarques

Si comparand et la valeur dans location1 sont égales, est value stocké dans location1. Dans le cas contraire, aucune opération n'est effectuée. Les opérations de comparaison et d’échange sont effectuées en tant qu’opération atomique. La valeur de retour de CompareExchange est la valeur d’origine dans location1, que l’échange ait lieu ou non.

Voir aussi

S’applique à

CompareExchange(Int16, Int16, Int16)

public:
 static short CompareExchange(short % location1, short value, short comparand);
public static short CompareExchange (ref short location1, short value, short comparand);
static member CompareExchange : int16 * int16 * int16 -> int16
Public Shared Function CompareExchange (ByRef location1 As Short, value As Short, comparand As Short) As Short

Paramètres

location1
Int16
value
Int16
comparand
Int16

Retours

S’applique à

CompareExchange(Double, Double, Double)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs

Compare deux nombres à virgule flottante double précision et remplace le premier en cas d'égalité.

public:
 static double CompareExchange(double % location1, double value, double comparand);
public static double CompareExchange (ref double location1, double value, double comparand);
static member CompareExchange : double * double * double -> double
Public Shared Function CompareExchange (ByRef location1 As Double, value As Double, comparand As Double) As Double

Paramètres

location1
Double

Destination, dont la valeur est comparée avec comparand et qui peut être remplacée.

value
Double

Valeur qui remplace la valeur de destination si la comparaison conclut à une égalité.

comparand
Double

Valeur comparée à celle de location1.

Retours

Valeur d’origine dans location1.

Exceptions

L’adresse de location1 est un pointeur null.

Exemples

L’exemple de code suivant illustre une méthode thread-safe qui accumule un total de valeurs en cours d’exécution Double . Deux threads ajoutent une série de valeurs à l’aide de Double la méthode thread-safe et de l’ajout ordinaire, et une fois les threads terminés, les totaux sont comparés. Sur un ordinateur à double processeur, il existe une différence significative dans les totaux.

Dans la méthode thread-safe, la valeur initiale du total en cours d’exécution est enregistrée, puis la CompareExchange méthode est utilisée pour échanger le total nouvellement calculé avec l’ancien total. Si la valeur de retour n’est pas égale à la valeur enregistrée du total en cours d’exécution, un autre thread a mis à jour le total entre-temps. Dans ce cas, la tentative de mise à jour du total en cours d’exécution doit être répétée.

// This example demonstrates a thread-safe method that adds to a
// running total.  
using System;
using System.Threading;

public class ThreadSafe
{
    // Field totalValue contains a running total that can be updated
    // by multiple threads. It must be protected from unsynchronized 
    // access.
    private double totalValue = 0.0;

    // The Total property returns the running total.
    public double Total { get { return totalValue; }}

    // AddToTotal safely adds a value to the running total.
    public double AddToTotal(double addend)
    {
        double initialValue, computedValue;
        do
        {
            // Save the current running total in a local variable.
            initialValue = totalValue;

            // Add the new value to the running total.
            computedValue = initialValue + addend;

            // CompareExchange compares totalValue to initialValue. If
            // they are not equal, then another thread has updated the
            // running total since this loop started. CompareExchange
            // does not update totalValue. CompareExchange returns the
            // contents of totalValue, which do not equal initialValue,
            // so the loop executes again.
        }
        while (initialValue != Interlocked.CompareExchange(ref totalValue, 
            computedValue, initialValue));
        // If no other thread updated the running total, then 
        // totalValue and initialValue are equal when CompareExchange
        // compares them, and computedValue is stored in totalValue.
        // CompareExchange returns the value that was in totalValue
        // before the update, which is equal to initialValue, so the 
        // loop ends.

        // The function returns computedValue, not totalValue, because
        // totalValue could be changed by another thread between
        // the time the loop ends and the function returns.
        return computedValue;
    }
}

public class Test
{
    // Create an instance of the ThreadSafe class to test.
    private static ThreadSafe ts = new ThreadSafe();
    private static double control;

    private static Random r = new Random();
    private static ManualResetEvent mre = new ManualResetEvent(false);

    public static void Main()
    {
        // Create two threads, name them, and start them. The
        // thread will block on mre.
        Thread t1 = new Thread(TestThread);
        t1.Name = "Thread 1";
        t1.Start();
        Thread t2 = new Thread(TestThread);
        t2.Name = "Thread 2";
        t2.Start();

        // Now let the threads begin adding random numbers to 
        // the total.
        mre.Set();
        
        // Wait until all the threads are done.
        t1.Join();
        t2.Join();

        Console.WriteLine("Thread safe: {0}  Ordinary Double: {1}", 
            ts.Total, control);
    }

    private static void TestThread()
    {
        // Wait until the signal.
        mre.WaitOne();

        for(int i = 1; i <= 1000000; i++)
        {
            // Add to the running total in the ThreadSafe instance, and
            // to an ordinary double.
            //
            double testValue = r.NextDouble();
            control += testValue;
            ts.AddToTotal(testValue);
        }
    }
}

/* On a dual-processor computer, this code example produces output 
   similar to the following:

Thread safe: 998068.049623744  Ordinary Double: 759775.417190589
 */
' This example demonstrates a thread-safe method that adds to a
' running total.  
Imports System.Threading

Public Class ThreadSafe
    ' Field totalValue contains a running total that can be updated
    ' by multiple threads. It must be protected from unsynchronized 
    ' access.
    Private totalValue As Double = 0.0

    ' The Total property returns the running total.
    Public ReadOnly Property Total As Double
        Get
            Return totalValue
        End Get
    End Property

    ' AddToTotal safely adds a value to the running total.
    Public Function AddToTotal(ByVal addend As Double) As Double
        Dim initialValue, computedValue As Double
        Do
            ' Save the current running total in a local variable.
            initialValue = totalValue

            ' Add the new value to the running total.
            computedValue = initialValue + addend

            ' CompareExchange compares totalValue to initialValue. If
            ' they are not equal, then another thread has updated the
            ' running total since this loop started. CompareExchange
            ' does not update totalValue. CompareExchange returns the
            ' contents of totalValue, which do not equal initialValue,
            ' so the loop executes again.
        Loop While initialValue <> Interlocked.CompareExchange( _
            totalValue, computedValue, initialValue)
        ' If no other thread updated the running total, then 
        ' totalValue and initialValue are equal when CompareExchange
        ' compares them, and computedValue is stored in totalValue.
        ' CompareExchange returns the value that was in totalValue
        ' before the update, which is equal to initialValue, so the 
        ' loop ends.

        ' The function returns computedValue, not totalValue, because
        ' totalValue could be changed by another thread between
        ' the time the loop ends and the function returns.
        Return computedValue
    End Function
End Class

Public Class Test
    ' Create an instance of the ThreadSafe class to test.
    Private Shared ts As New ThreadSafe()
    Private Shared control As Double

    Private Shared r As New Random()
    Private Shared mre As New ManualResetEvent(false)

    <MTAThread> _
    Public Shared Sub Main()
        ' Create two threads, name them, and start them. The
        ' threads will block on mre.
        Dim t1 As New Thread(AddressOf TestThread)
        t1.Name = "Thread 1"
        t1.Start()
        Dim t2 As New Thread(AddressOf TestThread)
        t2.Name = "Thread 2"
        t2.Start()

        ' Now let the threads begin adding random numbers to 
        ' the total.
        mre.Set()
        
        ' Wait until all the threads are done.
        t1.Join()
        t2.Join()

        Console.WriteLine("Thread safe: {0}  Ordinary Double: {1}", ts.Total, control)
    End Sub

    Private Shared Sub TestThread()
        ' Wait until the signal.
        mre.WaitOne()

        For i As Integer = 1 to 1000000
            ' Add to the running total in the ThreadSafe instance, and
            ' to an ordinary double.
            '
            Dim testValue As Double = r.NextDouble
            control += testValue
            ts.AddToTotal(testValue)
        Next
    End Sub
End Class

' On a dual-processor computer, this code example produces output 
' similar to the following:
'
'Thread safe: 998068.049623744  Ordinary Double: 759775.417190589

Remarques

Si comparand et la valeur dans location1 sont égales, est value stocké dans location1. Dans le cas contraire, aucune opération n'est effectuée. Les opérations de comparaison et d’échange sont effectuées en tant qu’opération atomique. La valeur de retour de CompareExchange est la valeur d’origine dans location1, que l’échange ait lieu ou non.

Voir aussi

S’applique à

CompareExchange(Byte, Byte, Byte)

public:
 static System::Byte CompareExchange(System::Byte % location1, System::Byte value, System::Byte comparand);
public static byte CompareExchange (ref byte location1, byte value, byte comparand);
static member CompareExchange : byte * byte * byte -> byte
Public Shared Function CompareExchange (ByRef location1 As Byte, value As Byte, comparand As Byte) As Byte

Paramètres

location1
Byte
value
Byte
comparand
Byte

Retours

S’applique à

CompareExchange(IntPtr, IntPtr, IntPtr)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs

Compare deux handles ou pointeurs spécifiques à la plateforme et remplace le premier en cas d’égalité.

public:
 static IntPtr CompareExchange(IntPtr % location1, IntPtr value, IntPtr comparand);
public static IntPtr CompareExchange (ref IntPtr location1, IntPtr value, IntPtr comparand);
static member CompareExchange : nativeint * nativeint * nativeint -> nativeint
Public Shared Function CompareExchange (ByRef location1 As IntPtr, value As IntPtr, comparand As IntPtr) As IntPtr

Paramètres

location1
IntPtr

nativeint

Destination IntPtr, dont la valeur est comparée à celle de comparand et qui peut être remplacée par value.

value
IntPtr

nativeint

Valeur IntPtr qui remplace la valeur de destination si la comparaison conclut à une égalité.

comparand
IntPtr

nativeint

Valeur IntPtr comparée à celle de location1.

Retours

IntPtr

nativeint

Valeur d’origine dans location1.

Exceptions

L’adresse de location1 est un pointeur null.

Remarques

Si comparand et la valeur dans location1 sont égales, est value stocké dans location1. Dans le cas contraire, aucune opération n'est effectuée. Les opérations de comparaison et d’échange sont effectuées en tant qu’opération atomique. La valeur de retour de cette méthode est la valeur d’origine dans location1, que l’échange ait lieu ou non.

Notes

IntPtr est un type spécifique à la plateforme.

Voir aussi

S’applique à

CompareExchange<T>(T, T, T)

Source:
Interlocked.CoreCLR.cs
Source:
Interlocked.CoreCLR.cs
Source:
Interlocked.CoreCLR.cs

Compare deux instances du type référence spécifié T pour et remplace la première en cas d’égalité par référence.

public:
generic <typename T>
 where T : class static T CompareExchange(T % location1, T value, T comparand);
public static T CompareExchange<T> (ref T location1, T value, T comparand) where T : class;
[System.Runtime.InteropServices.ComVisible(false)]
public static T CompareExchange<T> (ref T location1, T value, T comparand) where T : class;
static member CompareExchange : 'T * 'T * 'T -> 'T (requires 'T : null)
[<System.Runtime.InteropServices.ComVisible(false)>]
static member CompareExchange : 'T * 'T * 'T -> 'T (requires 'T : null)
Public Shared Function CompareExchange(Of T As Class) (ByRef location1 As T, value As T, comparand As T) As T

Paramètres de type

T

Type à utiliser pour location1, value et comparand. Ce type doit être un type référence.

Paramètres

location1
T

Destination dont la valeur est comparée par référence à comparand et qui peut être remplacée. C'est un paramètre référence (ref en C#, ByRef en Visual Basic).

value
T

Valeur qui remplace la valeur de destination si la comparaison par référence conclut à une égalité.

comparand
T

Valeur qui est comparée par référence à la valeur se trouvant à l’emplacement location1.

Retours

T

Valeur d’origine dans location1.

Attributs

Exceptions

L’adresse de location1 est un pointeur null.

Remarques

Si comparand et la valeur dans location1 sont égaux par référence, est value stocké dans location1. Dans le cas contraire, aucune opération n'est effectuée. La comparaison et l’échange sont effectués en tant qu’opération atomique. La valeur de retour de cette méthode est la valeur d’origine dans location1, que l’échange ait lieu ou non.

Cette méthode prend uniquement en charge les types de référence. Il existe des surcharges de la CompareExchange méthode pour les types Int32valeur , Int64, IntPtr, Singleet Double, mais il n’existe aucune prise en charge pour les autres types de valeurs.

Notes

Cette surcharge de méthode est préférable à la CompareExchange(Object, Object, Object) surcharge de méthode, car cette dernière nécessite l’accès à l’objet de destination pour une liaison tardive.

S’applique à