Interlocked.CompareExchange Interlocked.CompareExchange Interlocked.CompareExchange Interlocked.CompareExchange Method

定义

比较两个值是否相等,如果相等,则替换第一个值。Compares two values for equality and, if they are equal, replaces the first value.

重载

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, T) CompareExchange<T>(T, T, T) CompareExchange<T>(T, T, T) CompareExchange<T>(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)

比较两个双精度浮点数是否相等,如果相等,则替换第一个值。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
Public Shared Function CompareExchange (ByRef location1 As Double, value As Double, comparand As Double) As Double

参数

location1
Double Double Double Double

其值将与 comparand 进行比较并且可能被替换的目标。The destination, whose value is compared with comparand and possibly replaced.

value
Double Double Double Double

比较结果相等时替换目标值的值。The value that replaces the destination value if the comparison results in equality.

comparand
Double Double Double Double

与位于 location1 处的值进行比较的值。The value that is compared to the value at location1.

返回

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

异常

location1 的地址为空指针。The address of location1 is a null pointer.

示例

下面的代码示例演示了一种线程安全方法, 该方法累计Double值的运行总计。The following code example demonstrates a thread-safe method that accumulates a running total of Double values. 两个线程使用线程安全Double方法和普通加法添加一系列值, 并在线程完成合计时进行比较。Two threads add a series of Double values using the thread-safe method and ordinary addition, and when the threads complete the totals are compared. 在双处理器计算机上, 总计存在很大的差异。On a dual-processor computer, there is a significant difference in the totals.

在线程安全方法中, 保存 "运行总计" 的初始值, 然后CompareExchange使用方法来交换新计算的总计和旧总计。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. 如果返回值与运行总计的保存值不相等, 则另一个线程将同时更新总计。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. 在这种情况下, 必须重复更新运行总计的尝试。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;
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

注解

如果comparand和中location1的值相等, value则将存储在中location1If comparand and the value in location1 are equal, then value is stored in location1. 否则,不会执行任何操作。Otherwise, no operation is performed. 比较和交换操作以原子操作的方式执行。The compare and exchange operations are performed as an atomic operation. 的返回值CompareExchange为中location1的原始值, 无论是否发生交换都是如此。The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.

另请参阅

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.

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
Public Shared Function CompareExchange (ByRef location1 As Integer, value As Integer, comparand As Integer) As Integer

参数

location1
Int32 Int32 Int32 Int32

其值将与 comparand 进行比较并且可能被替换的目标。The destination, whose value is compared with comparand and possibly replaced.

value
Int32 Int32 Int32 Int32

比较结果相等时替换目标值的值。The value that replaces the destination value if the comparison results in equality.

comparand
Int32 Int32 Int32 Int32

与位于 location1 处的值进行比较的值。The value that is compared to the value at location1.

返回

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

异常

location1 的地址为空指针。The address of location1 is a null pointer.

示例

下面的代码示例演示累积运行总计的线程安全方法。The following code example demonstrates a thread-safe method that accumulates a running total. 保存 "运行总计" 的初始值, 然后CompareExchange使用方法来交换新计算的总计和旧总计。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. 如果返回值与运行总计的保存值不相等, 则另一个线程将同时更新总计。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. 在这种情况下, 必须重复更新运行总计的尝试。In that case, the attempt to update the running total must be repeated.

备注

.NET Framework Add的2.0 版中引入的方法提供了更方便的方法来累积整数的线程安全运行总计。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>

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

注解

如果comparand和中location1的值相等, value则将存储在中location1If comparand and the value in location1 are equal, then value is stored in location1. 否则,不会执行任何操作。Otherwise, no operation is performed. 比较和交换操作以原子操作的方式执行。The compare and exchange operations are performed as an atomic operation. 的返回值CompareExchange为中location1的原始值, 无论是否发生交换都是如此。The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.

另请参阅

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.

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
Public Shared Function CompareExchange (ByRef location1 As Long, value As Long, comparand As Long) As Long

参数

location1
Int64 Int64 Int64 Int64

其值将与 comparand 进行比较并且可能被替换的目标。The destination, whose value is compared with comparand and possibly replaced.

value
Int64 Int64 Int64 Int64

比较结果相等时替换目标值的值。The value that replaces the destination value if the comparison results in equality.

comparand
Int64 Int64 Int64 Int64

与位于 location1 处的值进行比较的值。The value that is compared to the value at location1.

返回

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

异常

location1 的地址为空指针。The address of location1 is a null pointer.

注解

如果comparand和中location1的值相等, value则将存储在中location1If comparand and the value in location1 are equal, then value is stored in location1. 否则,不会执行任何操作。Otherwise, no operation is performed. 比较和交换操作以原子操作的方式执行。The compare and exchange operations are performed as an atomic operation. 的返回值CompareExchange为中location1的原始值, 无论是否发生交换都是如此。The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.

另请参阅

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.

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
Public Shared Function CompareExchange (ByRef location1 As IntPtr, value As IntPtr, comparand As IntPtr) As IntPtr

参数

location1
IntPtr IntPtr IntPtr IntPtr

其值与 comparand 的值进行比较并且可能被 value 替换的目标 IntPtrThe destination IntPtr, whose value is compared with the value of comparand and possibly replaced by value.

value
IntPtr IntPtr IntPtr IntPtr

比较结果相等时替换目标值的 IntPtrThe IntPtr that replaces the destination value if the comparison results in equality.

comparand
IntPtr IntPtr IntPtr IntPtr

与位于 location1 处的值进行比较的 IntPtrThe IntPtr that is compared to the value at location1.

返回

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

异常

location1 的地址为空指针。The address of location1 is a null pointer.

注解

如果comparand和中location1的值相等, value则将存储在中location1If comparand and the value in location1 are equal, then value is stored in location1. 否则,不会执行任何操作。Otherwise, no operation is performed. 比较和交换操作以原子操作的方式执行。The compare and exchange operations are performed as an atomic operation. 此方法的返回值是中location1的原始值, 无论交换是否发生。The return value of this method is the original value in location1, whether or not the exchange takes place.

备注

IntPtr是特定于平台的类型。IntPtr is a platform-specific type.

另请参阅

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.

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
Public Shared Function CompareExchange (ByRef location1 As Object, value As Object, comparand As Object) As Object

参数

location1
Object Object Object Object

通过引用与 comparand 进行比较并且可能被替换的目标对象。The destination object that is compared by reference with comparand and possibly replaced.

value
Object Object Object Object

在引用比较结果相等时替换目标对象的对象。The object that replaces the destination object if the reference comparison results in equality.

comparand
Object Object Object Object

与位于 location1 处的对象通过引用进行比较的对象。The object that is compared by reference to the object at location1.

返回

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

异常

location1 的地址为空指针。The address of location1 is a null pointer.

注解

重要

从 .NET Framework 2.0 开始,CompareExchange<T>(T, T, T) 方法重载为引用类型提供类型安全的替代项。Beginning with .NET Framework 2.0, the CompareExchange<T>(T, T, T) method overload provides a type-safe alternative for reference types. 建议你调用它, 而不是此重载。We recommend that you call it instead of this overload.

如果comparand和中location1的对象是按引用value相等的, 则将存储location1在中。If comparand and the object in location1 are equal by reference, then value is stored in location1. 否则,不会执行任何操作。Otherwise, no operation is performed. 比较和交换操作以原子操作的方式执行。The compare and exchange operations are performed as an atomic operation. 的返回值CompareExchange为中location1的原始值, 无论是否发生交换都是如此。The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.

备注

对对象进行比较以确定引用是否相等, 而不是值相等。The objects are compared for reference equality rather than value equality. 因此, 相同值类型的两个装箱实例 (例如, 整数 3) 始终不相等, 并且不执行任何操作。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. 不要将此重载用于值类型。Do not use this overload with value types.

另请参阅

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.

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
Public Shared Function CompareExchange (ByRef location1 As Single, value As Single, comparand As Single) As Single

参数

location1
Single Single Single Single

其值将与 comparand 进行比较并且可能被替换的目标。The destination, whose value is compared with comparand and possibly replaced.

value
Single Single Single Single

比较结果相等时替换目标值的值。The value that replaces the destination value if the comparison results in equality.

comparand
Single Single Single Single

与位于 location1 处的值进行比较的值。The value that is compared to the value at location1.

返回

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

异常

location1 的地址为空指针。The address of location1 is a null pointer.

示例

下面的代码示例演示了一种线程安全方法, 该方法累计Single值的运行总计。The following code example demonstrates a thread-safe method that accumulates a running total of Single values. 两个线程使用线程安全Single方法和普通加法添加一系列值, 并在线程完成合计时进行比较。Two threads add a series of Single values using the thread-safe method and ordinary addition, and when the threads complete the totals are compared. 在双处理器计算机上, 总计存在很大的差异。On a dual-processor computer, there is a significant difference in the totals.

在线程安全方法中, 保存 "运行总计" 的初始值, 然后CompareExchange使用方法来交换新计算的总计和旧总计。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. 如果返回值与运行总计的保存值不相等, 则另一个线程将同时更新总计。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. 在这种情况下, 必须重复更新运行总计的尝试。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;
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

注解

如果comparand和中location1的值相等, value则将存储在中location1If comparand and the value in location1 are equal, then value is stored in location1. 否则,不会执行任何操作。Otherwise, no operation is performed. 比较和交换操作以原子操作的方式执行。The compare and exchange operations are performed as an atomic operation. 的返回值CompareExchange为中location1的原始值, 无论是否发生交换都是如此。The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.

另请参阅

CompareExchange<T>(T, T, T) CompareExchange<T>(T, T, T) CompareExchange<T>(T, T, T) CompareExchange<T>(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.

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 (requires 'T : null)
Public Shared Function CompareExchange(Of T As Class) (ByRef location1 As T, value As T, comparand As T) As T

类型参数

T

用于 location1valuecomparand 的类型。The type to be used for location1, value, and comparand. 此类型必须是引用类型。This type must be a reference type.

参数

location1
T T T T

其值通过引用与 comparand 进行比较并且可能被替换的目标。The destination, whose value is compared by reference with comparand and possibly replaced. 这是一个引用参数(在 C# 中是 ref,在 Visual Basic 中是 ByRef)。This is a reference parameter (ref in C#, ByRef in Visual Basic).

value
T T T T

引用比较结果相等时替换目标值的值。The value that replaces the destination value if the comparison by reference results in equality.

comparand
T T T T

与位于 location1 处的值通过引用进行比较的值。The value that is compared by reference to the value at location1.

返回

T T T T

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

异常

location1 的地址为空指针。The address of location1 is a null pointer.

注解

如果comparand和中location1的值value等于, 则将存储在中location1If comparand and the value in location1 are equal by reference, then value is stored in location1. 否则,不会执行任何操作。Otherwise, no operation is performed. 比较和交换是作为一个原子操作来执行的。The comparison and the exchange are performed as an atomic operation. 此方法的返回值是中location1的原始值, 无论交换是否发生。The return value of this method is the original value in location1, whether or not the exchange takes place.

此方法仅支持引用类型。This method only supports reference types. CompareExchange为值类型Int32Int64、、和Double提供方法的重载, 但不支持其他值类型。 IntPtr SingleThere 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.

备注

此方法重载优于CompareExchange(Object, Object, Object)方法重载, 因为后者需要后期绑定访问目标对象。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.

适用于