Compartir a través de


Interlocked.CompareExchange Método

Definición

Compara dos valores para la igualdad y, si son iguales, reemplaza el primer valor.

Sobrecargas

CompareExchange(UIntPtr, UIntPtr, UIntPtr)

Compara dos identificadores o punteros específicos de la plataforma para la igualdad y, si son iguales, reemplaza al primero.

CompareExchange(UInt64, UInt64, UInt64)

Compara dos enteros de 64 bits sin signo para obtener igualdad y, si son iguales, reemplaza el primer valor.

CompareExchange(UInt32, UInt32, UInt32)

Compara dos enteros de 32 bits sin signo para la igualdad y, si son iguales, reemplaza el primer valor.

CompareExchange(UInt16, UInt16, UInt16)

Compara dos enteros de 16 bits con signo para obtener igualdad y, si son iguales, reemplaza el primer valor.

CompareExchange(Single, Single, Single)

Compara dos números de punto flotante de precisión única para la igualdad y, si son iguales, reemplaza el primer valor.

CompareExchange(Object, Object, Object)

Compara dos objetos para la igualdad de referencia y, si son iguales, reemplaza al primer objeto.

CompareExchange(SByte, SByte, SByte)

Compara dos enteros de 8 bits con signo para obtener igualdad y, si son iguales, reemplaza el primer valor.

CompareExchange(Int64, Int64, Int64)

Compara dos enteros de 64 bits con signo para obtener igualdad y, si son iguales, reemplaza el primer valor.

CompareExchange(Int32, Int32, Int32)

Compara dos enteros de 32 bits con signo para obtener igualdad y, si son iguales, reemplaza el primer valor.

CompareExchange(Int16, Int16, Int16)

Compara dos enteros de 16 bits sin signo para la igualdad y, si son iguales, reemplaza el primer valor.

CompareExchange(Double, Double, Double)

Compara dos números de punto flotante de precisión doble para la igualdad y, si son iguales, reemplaza el primer valor.

CompareExchange(Byte, Byte, Byte)

Compara dos enteros sin signo de 8 bits para la igualdad y, si son iguales, reemplaza el primer valor.

CompareExchange(IntPtr, IntPtr, IntPtr)

Compara dos identificadores o punteros específicos de la plataforma para la igualdad y, si son iguales, reemplaza al primero.

CompareExchange<T>(T, T, T)

Compara dos instancias del tipo de referencia especificado T para la igualdad de referencia y, si son iguales, reemplaza al primero.

CompareExchange(UIntPtr, UIntPtr, UIntPtr)

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

Importante

Esta API no es conforme a CLS.

Compara dos identificadores o punteros específicos de la plataforma para la igualdad y, si son iguales, reemplaza al primero.

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

Parámetros

location1
UIntPtr

unativeint

El destino UIntPtr, cuyo valor se compara con el valor de comparand y posiblemente se reemplaza por value.

value
UIntPtr

unativeint

El UIntPtr que reemplaza el valor de destino si la comparación da como resultado la igualdad.

comparand
UIntPtr

unativeint

El UIntPtr que se compara con el valor en location1.

Devoluciones

UIntPtr

unativeint

Valor original de location1.

Atributos

Excepciones

La dirección de location1 es un puntero null.

Se aplica a

CompareExchange(UInt64, UInt64, UInt64)

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

Importante

Esta API no es conforme a CLS.

Compara dos enteros de 64 bits sin signo para obtener igualdad y, si son iguales, reemplaza el primer valor.

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

Parámetros

location1
UInt64

Destino, cuyo valor se compara con comparand y posiblemente se reemplaza.

value
UInt64

Valor que reemplaza el valor de destino si la comparación da como resultado la igualdad.

comparand
UInt64

Valor que se compara con el valor en location1.

Devoluciones

Valor original de location1.

Atributos

Excepciones

La dirección de location1 es un puntero null.

Se aplica a

CompareExchange(UInt32, UInt32, UInt32)

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

Importante

Esta API no es conforme a CLS.

Compara dos enteros de 32 bits sin signo para la igualdad y, si son iguales, reemplaza el primer valor.

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

Parámetros

location1
UInt32

Destino, cuyo valor se compara con comparand y posiblemente se reemplaza.

value
UInt32

Valor que reemplaza el valor de destino si la comparación da como resultado la igualdad.

comparand
UInt32

Valor que se compara con el valor en location1.

Devoluciones

Valor original de location1.

Atributos

Excepciones

La dirección de location1 es un puntero null.

Se aplica a

CompareExchange(UInt16, UInt16, UInt16)

Importante

Esta API no es conforme a CLS.

Compara dos enteros de 16 bits con signo para obtener igualdad y, si son iguales, reemplaza el primer valor.

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

Parámetros

location1
UInt16

Destino, cuyo valor se compara con comparand y posiblemente se reemplaza.

value
UInt16

Valor que reemplaza el valor de destino si la comparación da como resultado la igualdad.

comparand
UInt16

Valor que se compara con el valor en location1.

Devoluciones

Valor original de location1.

Atributos

Excepciones

La dirección de location1 es un puntero null.

Se aplica a

CompareExchange(Single, Single, Single)

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

Compara dos números de punto flotante de precisión única para la igualdad y, si son iguales, reemplaza el primer valor.

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

Parámetros

location1
Single

Destino, cuyo valor se compara con comparand y posiblemente se reemplaza.

value
Single

Valor que reemplaza el valor de destino si la comparación da como resultado la igualdad.

comparand
Single

Valor que se compara con el valor en location1.

Devoluciones

Valor original de location1.

Excepciones

La dirección de location1 es un puntero nulo.

Ejemplos

En el ejemplo de código siguiente se muestra un método seguro para subprocesos que acumula un total de valores de Single en ejecución. Dos subprocesos agregan una serie de valores de Single mediante el método seguro para subprocesos y la suma normal, y cuando los subprocesos completan los totales se comparan. En un equipo de doble procesador, hay una diferencia significativa en los totales.

En el método seguro para subprocesos, se guarda el valor inicial del total en ejecución y, a continuación, se usa el método CompareExchange para intercambiar el total recién calculado con el total anterior. Si el valor devuelto no es igual al valor guardado del total en ejecución, otro subproceso ha actualizado el total mientras tanto. En ese caso, el intento de actualizar el total en ejecución debe repetirse.

// 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

Comentarios

Si comparand y el valor de location1 son iguales, value se almacena en location1. De lo contrario, no se realiza ninguna operación. Las operaciones de comparación e intercambio se realizan como una operación atómica. El valor devuelto de CompareExchange es el valor original en location1, independientemente de si tiene lugar o no el intercambio.

Consulte también

Se aplica a

CompareExchange(Object, Object, Object)

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

Compara dos objetos para la igualdad de referencia y, si son iguales, reemplaza al primer objeto.

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

Parámetros

location1
Object

Objeto de destino que se compara por referencia con comparand y posiblemente reemplazado.

value
Object

Objeto que reemplaza al objeto de destino si la comparación de referencia da como resultado la igualdad.

comparand
Object

Objeto que se compara por referencia al objeto en location1.

Devoluciones

Valor original de location1.

Excepciones

La dirección de location1 es un puntero null.

Comentarios

Importante

A partir de .NET Framework 2.0, la sobrecarga del método CompareExchange<T>(T, T, T) proporciona una alternativa segura para tipos de referencia. Se recomienda llamarlo en lugar de esta sobrecarga.

Si comparand y el objeto de location1 son iguales por referencia, value se almacena en location1. De lo contrario, no se realiza ninguna operación. Las operaciones de comparación e intercambio se realizan como una operación atómica. El valor devuelto de CompareExchange es el valor original en location1, independientemente de si tiene lugar o no el intercambio.

Nota

Los objetos se comparan con la igualdad de referencia en lugar de la igualdad de valores. Como resultado, dos instancias boxadas del mismo tipo de valor (por ejemplo, el entero 3) siempre parecen ser desiguales y no se realiza ninguna operación. No use esta sobrecarga con tipos de valor.

Consulte también

Se aplica a

CompareExchange(SByte, SByte, SByte)

Importante

Esta API no es conforme a CLS.

Compara dos enteros de 8 bits con signo para obtener igualdad y, si son iguales, reemplaza el primer valor.

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

Parámetros

location1
SByte

Destino, cuyo valor se compara con comparand y posiblemente se reemplaza.

value
SByte

Valor que reemplaza el valor de destino si la comparación da como resultado la igualdad.

comparand
SByte

Valor que se compara con el valor en location1.

Devoluciones

Valor original de location1.

Atributos

Excepciones

La dirección de location1 es un puntero null.

Se aplica a

CompareExchange(Int64, Int64, Int64)

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

Compara dos enteros de 64 bits con signo para obtener igualdad y, si son iguales, reemplaza el primer valor.

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

Parámetros

location1
Int64

Destino, cuyo valor se compara con comparand y posiblemente se reemplaza.

value
Int64

Valor que reemplaza el valor de destino si la comparación da como resultado la igualdad.

comparand
Int64

Valor que se compara con el valor en location1.

Devoluciones

Valor original de location1.

Excepciones

La dirección de location1 es un puntero nulo.

Comentarios

Si comparand y el valor de location1 son iguales, value se almacena en location1. De lo contrario, no se realiza ninguna operación. Las operaciones de comparación e intercambio se realizan como una operación atómica. El valor devuelto de CompareExchange es el valor original en location1, independientemente de si tiene lugar o no el intercambio.

Consulte también

Se aplica a

CompareExchange(Int32, Int32, Int32)

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

Compara dos enteros de 32 bits con signo para obtener igualdad y, si son iguales, reemplaza el primer valor.

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

Parámetros

location1
Int32

Destino, cuyo valor se compara con comparand y posiblemente se reemplaza.

value
Int32

Valor que reemplaza el valor de destino si la comparación da como resultado la igualdad.

comparand
Int32

Valor que se compara con el valor en location1.

Devoluciones

Valor original de location1.

Excepciones

La dirección de location1 es un puntero nulo.

Ejemplos

En el ejemplo de código siguiente se muestra un método seguro para subprocesos que acumula un total en ejecución. El valor inicial del total en ejecución se guarda y, a continuación, el método CompareExchange se usa para intercambiar el total recién calculado con el total anterior. Si el valor devuelto no es igual al valor guardado del total en ejecución, otro subproceso ha actualizado el total mientras tanto. En ese caso, el intento de actualizar el total en ejecución debe repetirse.

Nota

El método Add, introducido en la versión 2.0 de .NET Framework, proporciona una manera más cómoda de acumular totales de ejecución seguros para subprocesos para enteros.

// 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

Comentarios

Si comparand y el valor de location1 son iguales, value se almacena en location1. De lo contrario, no se realiza ninguna operación. Las operaciones de comparación e intercambio se realizan como una operación atómica. El valor devuelto de CompareExchange es el valor original en location1, independientemente de si tiene lugar o no el intercambio.

Consulte también

Se aplica a

CompareExchange(Int16, Int16, Int16)

Compara dos enteros de 16 bits sin signo para la igualdad y, si son iguales, reemplaza el primer valor.

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

Parámetros

location1
Int16

Destino, cuyo valor se compara con comparand y posiblemente se reemplaza.

value
Int16

Valor que reemplaza el valor de destino si la comparación da como resultado la igualdad.

comparand
Int16

Valor que se compara con el valor en location1.

Devoluciones

Valor original de location1.

Excepciones

La dirección de location1 es un puntero null.

Se aplica a

CompareExchange(Double, Double, Double)

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

Compara dos números de punto flotante de precisión doble para la igualdad y, si son iguales, reemplaza el primer valor.

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

Parámetros

location1
Double

Destino, cuyo valor se compara con comparand y posiblemente se reemplaza.

value
Double

Valor que reemplaza el valor de destino si la comparación da como resultado la igualdad.

comparand
Double

Valor que se compara con el valor en location1.

Devoluciones

Valor original de location1.

Excepciones

La dirección de location1 es un puntero nulo.

Ejemplos

En el ejemplo de código siguiente se muestra un método seguro para subprocesos que acumula un total de valores de Double en ejecución. Dos subprocesos agregan una serie de valores de Double mediante el método seguro para subprocesos y la suma normal, y cuando los subprocesos completan los totales se comparan. En un equipo de doble procesador, hay una diferencia significativa en los totales.

En el método seguro para subprocesos, se guarda el valor inicial del total en ejecución y, a continuación, se usa el método CompareExchange para intercambiar el total recién calculado con el total anterior. Si el valor devuelto no es igual al valor guardado del total en ejecución, otro subproceso ha actualizado el total mientras tanto. En ese caso, el intento de actualizar el total en ejecución debe repetirse.

// 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

Comentarios

Si comparand y el valor de location1 son iguales, value se almacena en location1. De lo contrario, no se realiza ninguna operación. Las operaciones de comparación e intercambio se realizan como una operación atómica. El valor devuelto de CompareExchange es el valor original en location1, independientemente de si tiene lugar o no el intercambio.

Consulte también

Se aplica a

CompareExchange(Byte, Byte, Byte)

Compara dos enteros sin signo de 8 bits para la igualdad y, si son iguales, reemplaza el primer valor.

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

Parámetros

location1
Byte

Destino, cuyo valor se compara con comparand y posiblemente se reemplaza.

value
Byte

Valor que reemplaza el valor de destino si la comparación da como resultado la igualdad.

comparand
Byte

Valor que se compara con el valor en location1.

Devoluciones

Valor original de location1.

Excepciones

La dirección de location1 es un puntero null.

Se aplica a

CompareExchange(IntPtr, IntPtr, IntPtr)

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

Compara dos identificadores o punteros específicos de la plataforma para la igualdad y, si son iguales, reemplaza al primero.

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

Parámetros

location1
IntPtr

nativeint

El destino IntPtr, cuyo valor se compara con el valor de comparand y posiblemente se reemplaza por value.

value
IntPtr

nativeint

El IntPtr que reemplaza el valor de destino si la comparación da como resultado la igualdad.

comparand
IntPtr

nativeint

El IntPtr que se compara con el valor en location1.

Devoluciones

IntPtr

nativeint

Valor original de location1.

Excepciones

La dirección de location1 es un puntero nulo.

Comentarios

Si comparand y el valor de location1 son iguales, value se almacena en location1. De lo contrario, no se realiza ninguna operación. Las operaciones de comparación e intercambio se realizan como una operación atómica. El valor devuelto de este método es el valor original de location1, independientemente de que se produzca o no el intercambio.

Nota

IntPtr es un tipo específico de la plataforma.

Consulte también

Se aplica a

CompareExchange<T>(T, T, T)

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

Compara dos instancias del tipo de referencia especificado T para la igualdad de referencia y, si son iguales, reemplaza al primero.

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

Parámetros de tipo

T

Tipo que se va a usar para location1, valuey comparand. Este tipo debe ser un tipo de referencia.

Parámetros

location1
T

Destino, cuyo valor se compara por referencia con comparand y posiblemente se reemplaza. Se trata de un parámetro de referencia (ref en C#, ByRef en Visual Basic).

value
T

Valor que reemplaza el valor de destino si la comparación por referencia da como resultado la igualdad.

comparand
T

Valor que se compara por referencia al valor en location1.

Devoluciones

T

Valor original de location1.

Atributos

Excepciones

La dirección de location1 es un puntero nulo.

Se especifica un T no admitido.

Comentarios

Si comparand y el valor de location1 son iguales por referencia, value se almacena en location1. De lo contrario, no se realiza ninguna operación. La comparación y el intercambio se realizan como una operación atómica. El valor devuelto de este método es el valor original de location1, independientemente de que se produzca o no el intercambio.

Este método solo admite tipos de referencia. Hay sobrecargas del método CompareExchange para los tipos de valor Int32, Int64, IntPtr, Singley Double, pero no hay compatibilidad con otros tipos de valor.

Nota

Esta sobrecarga de método es preferible a la sobrecarga del método CompareExchange(Object, Object, Object), ya que esta última requiere que se acceda al objeto de destino enlazado en tiempo de ejecución.

Se aplica a