Interlocked.CompareExchangeInterlocked.CompareExchangeInterlocked.CompareExchangeInterlocked.CompareExchange Method

Definição

Compara dois valores para verificar se são iguais e, em caso de igualdade, substitui o primeiro valor.Compares two values for equality and, if they are equal, replaces the first value.

Sobrecargas

 CompareExchange(Double, Double, Double) CompareExchange(Double, Double, Double) CompareExchange(Double, Double, Double) CompareExchange(Double, Double, Double) Compara se dois pontos flutuantes de precisão dupla são iguais e, se eles forem, substitui o primeiro valor.Compares two double-precision floating point numbers for equality and, if they are equal, replaces the first value. CompareExchange(Int32, Int32, Int32) CompareExchange(Int32, Int32, Int32) CompareExchange(Int32, Int32, Int32) CompareExchange(Int32, Int32, Int32) Compara dois inteiros com sinal de 32 bits para verificar se são iguais e, em caso de igualdade, substitui o primeiro valor.Compares two 32-bit signed integers for equality and, if they are equal, replaces the first value. CompareExchange(Int64, Int64, Int64) CompareExchange(Int64, Int64, Int64) CompareExchange(Int64, Int64, Int64) CompareExchange(Int64, Int64, Int64) Compara dois inteiros com sinal de 64 bits para verificar se são iguais e, em caso de igualdade, substitui o primeiro valor.Compares two 64-bit signed integers for equality and, if they are equal, replaces the first value. CompareExchange(IntPtr, IntPtr, IntPtr) CompareExchange(IntPtr, IntPtr, IntPtr) CompareExchange(IntPtr, IntPtr, IntPtr) CompareExchange(IntPtr, IntPtr, IntPtr) Compara dois ponteiros ou identificadores específicos da plataforma quanto à igualdade e, se eles são iguais, substitui o primeiro.Compares two platform-specific handles or pointers for equality and, if they are equal, replaces the first one. CompareExchange(Object, Object, Object) CompareExchange(Object, Object, Object) CompareExchange(Object, Object, Object) CompareExchange(Object, Object, Object) Compara dois objetos quanto à igualdade de referência e, se eles forem iguais, substitui o primeiro objeto.Compares two objects for reference equality and, if they are equal, replaces the first object. CompareExchange(Single, Single, Single) CompareExchange(Single, Single, Single) CompareExchange(Single, Single, Single) CompareExchange(Single, Single, Single) Compara se dois números de ponto flutuante de precisão simples são iguais e, se eles são, substitui o primeiro valor.Compares two single-precision floating point numbers for equality and, if they are equal, replaces the first value. CompareExchange(T, T, T) CompareExchange(T, T, T) CompareExchange(T, T, T) CompareExchange(T, T, T) Compara duas instâncias do tipo de referência T especificado em relação à igualdade e, se elas forem iguais, substitui a primeira.Compares two instances of the specified reference type T for reference equality and, if they are equal, replaces the first one.

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

Compara se dois pontos flutuantes de precisão dupla são iguais e, se eles forem, substitui o primeiro valor.Compares two double-precision floating point numbers for equality and, if they are equal, replaces the first value.

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

O destino, cujo valor é comparado com comparand e possivelmente substituído.The destination, whose value is compared with comparand and possibly replaced.

value
Double Double Double Double

O valor que substitui o valor de destino quando a comparação resulta em igualdade.The value that replaces the destination value if the comparison results in equality.

comparand
Double Double Double Double

O valor comparado ao valor em location1.The value that is compared to the value at location1.

Retornos

O valor original em location1.The original value in location1.

Exceções

O endereço de location1 é um ponteiro nulo.The address of location1 is a null pointer.

Exemplos

No método thread-safe, o valor inicial do total acumulado é salvo e o CompareExchange método é usado para trocar o total computado recentemente pelo total antigo.In the thread-safe method, the initial value of the running total is saved, and then the CompareExchange method is used to exchange the newly computed total with the old total. Se o valor de retorno não for igual ao valor salvo do total em execução, então outro thread terá atualizado o total enquanto isso.If the return value is not equal to the saved value of the running total, then another thread has updated the total in the meantime. Nesse caso, a tentativa de atualizar o total cumulativo deve ser repetida.In that case, the attempt to update the running total must be repeated.

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

{
// 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.
{
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.
t1.Name = "Thread 1";
t1.Start();
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;
}
}
}

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

' 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
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)

Public Shared Sub Main()
' Create two threads, name them, and start them. The
' threads will block on mre.
t1.Name = "Thread 1"
t1.Start()
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
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

Comentários

Se comparand e o valor em location1 forem iguais, value será armazenado em location1.If comparand and the value in location1 are equal, then value is stored in location1. Caso contrário, nenhuma operação será executada.Otherwise, no operation is performed. As operações compare e Exchange são executadas como uma operação atômica.The compare and exchange operations are performed as an atomic operation. O valor de retorno CompareExchange de é o valor original location1no, se o intercâmbio ocorre ou não.The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.

Veja também

CompareExchange(Int32, Int32, Int32)CompareExchange(Int32, Int32, Int32)CompareExchange(Int32, Int32, Int32)CompareExchange(Int32, Int32, Int32)

Compara dois inteiros com sinal de 32 bits para verificar se são iguais e, em caso de igualdade, substitui o primeiro valor.Compares two 32-bit signed integers for equality and, if they are equal, replaces the first value.

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

O destino, cujo valor é comparado com comparand e possivelmente substituído.The destination, whose value is compared with comparand and possibly replaced.

value
Int32 Int32 Int32 Int32

O valor que substitui o valor de destino quando a comparação resulta em igualdade.The value that replaces the destination value if the comparison results in equality.

comparand
Int32 Int32 Int32 Int32

O valor comparado ao valor em location1.The value that is compared to the value at location1.

Retornos

O valor original em location1.The original value in location1.

Exceções

O endereço de location1 é um ponteiro nulo.The address of location1 is a null pointer.

Exemplos

O exemplo de código a seguir demonstra um método thread-safe que acumula um total em execução.The following code example demonstrates a thread-safe method that accumulates a running total. O valor inicial do total acumulado é salvo e, em seguida CompareExchange , o método é usado para trocar o total calculado recentemente pelo total antigo.The initial value of the running total is saved, and then the CompareExchange method is used to exchange the newly computed total with the old total. Se o valor de retorno não for igual ao valor salvo do total em execução, então outro thread terá atualizado o total enquanto isso.If the return value is not equal to the saved value of the running total, then another thread has updated the total in the meantime. Nesse caso, a tentativa de atualizar o total cumulativo deve ser repetida.In that case, the attempt to update the running total must be repeated.

Observação

O Add método, introduzido na versão 2,0 do .NET Framework, fornece uma maneira mais conveniente de acumular totais de execução segura para thread para inteiros.The Add method, introduced in version 2.0 of the .NET Framework, provides a more convenient way to accumulate thread-safe running totals for integers.

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

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()
{
}

}

// AddToTotal safely adds a value to the running total.
{
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.

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

// AddToTotal safely adds a value to the running total.
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.

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

Comentários

Se comparand e o valor em location1 forem iguais, value será armazenado em location1.If comparand and the value in location1 are equal, then value is stored in location1. Caso contrário, nenhuma operação será executada.Otherwise, no operation is performed. As operações compare e Exchange são executadas como uma operação atômica.The compare and exchange operations are performed as an atomic operation. O valor de retorno CompareExchange de é o valor original location1no, se o intercâmbio ocorre ou não.The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.

Veja também

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

Compara dois inteiros com sinal de 64 bits para verificar se são iguais e, em caso de igualdade, substitui o primeiro valor.Compares two 64-bit signed integers for equality and, if they are equal, replaces the first value.

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

O destino, cujo valor é comparado com comparand e possivelmente substituído.The destination, whose value is compared with comparand and possibly replaced.

value
Int64 Int64 Int64 Int64

O valor que substitui o valor de destino quando a comparação resulta em igualdade.The value that replaces the destination value if the comparison results in equality.

comparand
Int64 Int64 Int64 Int64

O valor comparado ao valor em location1.The value that is compared to the value at location1.

Retornos

O valor original em location1.The original value in location1.

Exceções

O endereço de location1 é um ponteiro nulo.The address of location1 is a null pointer.

Comentários

Se comparand e o valor em location1 forem iguais, value será armazenado em location1.If comparand and the value in location1 are equal, then value is stored in location1. Caso contrário, nenhuma operação será executada.Otherwise, no operation is performed. As operações compare e Exchange são executadas como uma operação atômica.The compare and exchange operations are performed as an atomic operation. O valor de retorno CompareExchange de é o valor original location1no, se o intercâmbio ocorre ou não.The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.

Veja também

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

Compara dois ponteiros ou identificadores específicos da plataforma quanto à igualdade e, se eles são iguais, substitui o primeiro.Compares two platform-specific handles or pointers for equality and, if they are equal, replaces the first one.

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

O IntPtr de destino, cujo valor é comparado com o valor de comparand e possivelmente substituído por value.The destination IntPtr, whose value is compared with the value of comparand and possibly replaced by value.

value
IntPtr IntPtr IntPtr IntPtr

O IntPtr que substitui o valor de destino quando a comparação resulta em igualdade.The IntPtr that replaces the destination value if the comparison results in equality.

comparand
IntPtr IntPtr IntPtr IntPtr

O IntPtr comparado ao valor em location1.The IntPtr that is compared to the value at location1.

Retornos

O valor original em location1.The original value in location1.

Exceções

O endereço de location1 é um ponteiro nulo.The address of location1 is a null pointer.

Comentários

Se comparand e o valor em location1 forem iguais, value será armazenado em location1.If comparand and the value in location1 are equal, then value is stored in location1. Caso contrário, nenhuma operação será executada.Otherwise, no operation is performed. As operações compare e Exchange são executadas como uma operação atômica.The compare and exchange operations are performed as an atomic operation. O valor de retorno desse método é o valor original no location1, se o intercâmbio ocorre ou não.The return value of this method is the original value in location1, whether or not the exchange takes place.

Observação

IntPtré um tipo específico da plataforma.IntPtr is a platform-specific type.

Veja também

CompareExchange(Object, Object, Object)CompareExchange(Object, Object, Object)CompareExchange(Object, Object, Object)CompareExchange(Object, Object, Object)

Compara dois objetos quanto à igualdade de referência e, se eles forem iguais, substitui o primeiro objeto.Compares two objects for reference equality and, if they are equal, replaces the first object.

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);
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 Object Object Object

O objeto de destino que é comparado pela referência com comparand e possivelmente substituído.The destination object that is compared by reference with comparand and possibly replaced.

value
Object Object Object Object

O objeto que substitui o objeto de destino quando a comparação de referência resulta em igualdade.The object that replaces the destination object if the reference comparison results in equality.

comparand
Object Object Object Object

O objeto que é comparado pela referência ao objeto em location1.The object that is compared by reference to the object at location1.

Retornos

O valor original em location1.The original value in location1.

Exceções

O endereço de location1 é um ponteiro nulo.The address of location1 is a null pointer.

Comentários

Importante

Começando com o .NET Framework 2.0, a sobrecarga do método CompareExchange<T>(T, T, T) fornece uma alternativa fortemente tipada para tipos de referência.Beginning with .NET Framework 2.0, the CompareExchange<T>(T, T, T) method overload provides a type-safe alternative for reference types. É recomendável chamá-lo em vez dessa sobrecarga.We recommend that you call it instead of this overload.

Se comparand e o objeto no location1 forem value iguais por referência, será armazenado em location1.If comparand and the object in location1 are equal by reference, then value is stored in location1. Caso contrário, nenhuma operação será executada.Otherwise, no operation is performed. As operações compare e Exchange são executadas como uma operação atômica.The compare and exchange operations are performed as an atomic operation. O valor de retorno CompareExchange de é o valor original location1no, se o intercâmbio ocorre ou não.The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.

Observação

Os objetos são comparados para igualdade de referência em vez de valor igualdade.The objects are compared for reference equality rather than value equality. Como resultado, duas instâncias emolduradas do mesmo tipo de valor (por exemplo, o inteiro 3) sempre parecem ser desiguais e nenhuma operação é executada.As a result, two boxed instances of the same value type (for example, the integer 3) always appear to be unequal and no operation is performed. Não use essa sobrecarga com tipos de valor.Do not use this overload with value types.

Veja também

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

Compara se dois números de ponto flutuante de precisão simples são iguais e, se eles são, substitui o primeiro valor.Compares two single-precision floating point numbers for equality and, if they are equal, replaces the first value.

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

O destino, cujo valor é comparado com comparand e possivelmente substituído.The destination, whose value is compared with comparand and possibly replaced.

value
Single Single Single Single

O valor que substitui o valor de destino quando a comparação resulta em igualdade.The value that replaces the destination value if the comparison results in equality.

comparand
Single Single Single Single

O valor comparado ao valor em location1.The value that is compared to the value at location1.

Retornos

O valor original em location1.The original value in location1.

Exceções

O endereço de location1 é um ponteiro nulo.The address of location1 is a null pointer.

Exemplos

No método thread-safe, o valor inicial do total acumulado é salvo e o CompareExchange método é usado para trocar o total computado recentemente pelo total antigo.In the thread-safe method, the initial value of the running total is saved, and then the CompareExchange method is used to exchange the newly computed total with the old total. Se o valor de retorno não for igual ao valor salvo do total em execução, então outro thread terá atualizado o total enquanto isso.If the return value is not equal to the saved value of the running total, then another thread has updated the total in the meantime. Nesse caso, a tentativa de atualizar o total cumulativo deve ser repetida.In that case, the attempt to update the running total must be repeated.

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

{
// 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.
{
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.
t1.Name = "Thread 1";
t1.Start();
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;
}
}
}

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

' 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
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)

Public Shared Sub Main()
' Create two threads, name them, and start them. The
' threads will block on mre.
t1.Name = "Thread 1"
t1.Start()
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
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

Comentários

Se comparand e o valor em location1 forem iguais, value será armazenado em location1.If comparand and the value in location1 are equal, then value is stored in location1. Caso contrário, nenhuma operação será executada.Otherwise, no operation is performed. As operações compare e Exchange são executadas como uma operação atômica.The compare and exchange operations are performed as an atomic operation. O valor de retorno CompareExchange de é o valor original location1no, se o intercâmbio ocorre ou não.The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.

Veja também

CompareExchange<T>(T, T, T)CompareExchange<T>(T, T, T)CompareExchange<T>(T, T, T)CompareExchange<T>(T, T, T)

Compara duas instâncias do tipo de referência T especificado em relação à igualdade e, se elas forem iguais, substitui a primeira.Compares two instances of the specified reference type T for reference equality and, if they are equal, replaces the first one.

public:
generic <typename T>
where T : class static T CompareExchange(T % location1, T value, T comparand);
[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)
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

O tipo a ser usado para location1, value e comparand.The type to be used for location1, value, and comparand. Esse tipo deve ser um tipo de referência.This type must be a reference type.

Parâmetros

location1
T T T T

O destino, cujo valor é comparado por referência com comparand e possivelmente substituído.The destination, whose value is compared by reference with comparand and possibly replaced. Esse é um parâmetro de referência (ref no C# e ByRef no Visual Basic).This is a reference parameter (ref in C#, ByRef in Visual Basic).

value
T T T T

O valor que substitui o valor de destino quando a comparação pela referência resulta em igualdade.The value that replaces the destination value if the comparison by reference results in equality.

comparand
T T T T

O valor que é comparado pela referência com o valor em location1.The value that is compared by reference to the value at location1.

Retornos

T T T T

O valor original em location1.The original value in location1.

Exceções

O endereço de location1 é um ponteiro nulo.The address of location1 is a null pointer.

Comentários

Se comparand e o valor em location1 forem value iguais por referência, será armazenado em location1.If comparand and the value in location1 are equal by reference, then value is stored in location1. Caso contrário, nenhuma operação será executada.Otherwise, no operation is performed. A comparação e a troca são executadas como uma operação atômica.The comparison and the exchange are performed as an atomic operation. O valor de retorno desse método é o valor original no location1, se o intercâmbio ocorre ou não.The return value of this method is the original value in location1, whether or not the exchange takes place.

Este método só dá suporte a tipos de referência.This method only supports reference types. Há sobrecargas CompareExchange do método para os tipos Int32de valor, Int64, IntPtr Single, e Double, mas não há suporte para outros tipos de valor.There are overloads of the CompareExchange method for the value types Int32, Int64, IntPtr, Single, and Double, but there is no support for other value types.

Observação

Essa sobrecarga de método é preferível CompareExchange(Object, Object, Object) à sobrecarga do método, pois o último requer que o objeto de destino seja acessado com associação tardia.This method overload is preferable to the CompareExchange(Object, Object, Object) method overload, because the latter requires the destination object to be accessed late-bound.