# Interlocked.CompareExchangeInterlocked.CompareExchangeInterlocked.CompareExchangeInterlocked.CompareExchange Method

## 多載

 CompareExchange(Double, Double, Double) CompareExchange(Double, Double, Double) CompareExchange(Double, Double, Double) CompareExchange(Double, Double, Double) 比較兩個雙精確度浮點數是否相等；如果相等，則取代第一個值。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) 比較兩個 32 位元帶正負號的整數是否相等，如果相等，則取代第一個值。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) 比較兩個 64 位元帶正負號的整數是否相等，如果相等，則取代第一個值。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) 比較兩個平台特定的控制代碼或指標是否相等；如果相等，則取代第一個。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) 比較兩個物件的參考是否相等；如果相等，則取代第一個物件。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) 比較兩個單精確度浮點數是否相等；如果相等，則取代第一個值。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) 比較指定參考型別 `T` 的兩個執行個體是否參考相等；如果相等，則取代第一個。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)

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

#### 參數

location1
Double Double Double Double

value
Double Double Double Double

comparand
Double Double Double Double

`location1` 的值比較的值。The value that is compared to the value at `location1`.

#### 傳回

`location1` 中的原始值。The original value in `location1`.

#### 例外狀況

`location1` 的位址為 null 指標。The address of `location1` is a null pointer.

### 範例

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

{
double initialValue, computedValue;
do
{
// Save the current running total in a local variable.
initialValue = totalValue;

// Add the new value to the running total.

// 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 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.Start();
t2.Start();

// 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);
}

{
// Wait until the signal.
mre.WaitOne();

for(int i = 1; i <= 1000000; i++)
{
// 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

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.

' 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.Start()
t2.Start()

' 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

' Wait until the signal.
mre.WaitOne()

For i As Integer = 1 to 1000000
' 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
``````

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

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

#### 參數

location1
Int32 Int32 Int32 Int32

value
Int32 Int32 Int32 Int32

comparand
Int32 Int32 Int32 Int32

`location1` 的值比較的值。The value that is compared to the value at `location1`.

#### 傳回

`location1` 中的原始值。The original value in `location1`.

#### 例外狀況

`location1` 的位址為 null 指標。The address of `location1` is a null pointer.

### 範例

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

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

}

{
int initialValue;
int computedValue;
do
{

// Save the current running total in a local variable.
initialValue = totalValue;

// Add the new value to the running total.

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

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

int initialValue, computedValue;
do {
// Save the current running total in a local variable.
initialValue = totalValue;

// Add the new value to the running total.

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

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.

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

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

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

#### 參數

location1
Int64 Int64 Int64 Int64

value
Int64 Int64 Int64 Int64

comparand
Int64 Int64 Int64 Int64

`location1` 的值比較的值。The value that is compared to the value at `location1`.

#### 傳回

`location1` 中的原始值。The original value in `location1`.

#### 例外狀況

`location1` 的位址為 null 指標。The address of `location1` is a null pointer.

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

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

#### 參數

location1
IntPtr IntPtr IntPtr IntPtr

IntPtr 目的端，其值會與 `comparand` 的值進行比較，且可能被 `value` 所取代。The destination IntPtr, whose value is compared with the value of `comparand` and possibly replaced by `value`.

value
IntPtr IntPtr IntPtr IntPtr

IntPtr，當比較的結果相等時會取代目的端值。The IntPtr that replaces the destination value if the comparison results in equality.

comparand
IntPtr IntPtr IntPtr IntPtr

IntPtr，會與 `location1` 的值相比較。The IntPtr that is compared to the value at `location1`.

#### 傳回

`location1` 中的原始值。The original value in `location1`.

#### 例外狀況

`location1` 的位址為 null 指標。The address of `location1` is a null pointer.

### 備註

IntPtr是平臺特定的類型。IntPtr is a platform-specific type.

## CompareExchange(Object, Object, Object)CompareExchange(Object, Object, Object)CompareExchange(Object, Object, Object)CompareExchange(Object, Object, 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``

#### 參數

location1
Object Object Object Object

value
Object Object Object Object

comparand
Object Object Object Object

#### 傳回

`location1` 中的原始值。The original value in `location1`.

#### 例外狀況

`location1` 的位址為 null 指標。The address of `location1` is a null pointer.

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

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

#### 參數

location1
Single Single Single Single

value
Single Single Single Single

comparand
Single Single Single Single

`location1` 的值比較的值。The value that is compared to the value at `location1`.

#### 傳回

`location1` 中的原始值。The original value in `location1`.

#### 例外狀況

`location1` 的位址為 null 指標。The address of `location1` is a null pointer.

### 範例

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

{
float initialValue, computedValue;
do
{
// Save the current running total in a local variable.
initialValue = totalValue;

// Add the new value to the running total.

// 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 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.Start();
t2.Start();

// 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);
}

{
// Wait until the signal.
mre.WaitOne();

for(int i = 1; i <= 1000000; i++)
{
// 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

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.

' 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.Start()
t2.Start()

' 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

' Wait until the signal.
mre.WaitOne()

For i As Integer = 1 to 1000000
' 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
``````

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

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

T

location1
T T T T

value
T T T T

comparand
T T T T

#### 傳回

T T T T

`location1` 中的原始值。The original value in `location1`.

#### 例外狀況

`location1` 的位址為 null 指標。The address of `location1` is a null pointer.