共用方式為


Interlocked.CompareExchange 方法

定義

比較兩個值是否相等,如果相等,則會取代第一個值。

多載

CompareExchange(UIntPtr, UIntPtr, UIntPtr)

比較兩個平臺特定句柄或指標是否相等,如果相等,則會取代第一個句柄。

CompareExchange(UInt64, UInt64, UInt64)

比較兩個 64 位無符號整數是否相等,如果相等,則會取代第一個值。

CompareExchange(UInt32, UInt32, UInt32)

比較兩個 32 位無符號整數是否相等,如果相等,則會取代第一個值。

CompareExchange(UInt16, UInt16, UInt16)

比較兩個 16 位帶正負號的整數是否相等,如果相等,則會取代第一個值。

CompareExchange(Single, Single, Single)

比較兩個單精度浮點數是否相等,如果相等,則會取代第一個值。

CompareExchange(Object, Object, Object)

比較兩個對象的參考相等,如果相等,則會取代第一個物件。

CompareExchange(SByte, SByte, SByte)

比較兩個 8 位帶正負號的整數是否相等,如果相等,則會取代第一個值。

CompareExchange(Int64, Int64, Int64)

比較兩個 64 位帶正負號的整數是否相等,如果相等,則會取代第一個值。

CompareExchange(Int32, Int32, Int32)

比較兩個 32 位帶正負號的整數是否相等,如果相等,則會取代第一個值。

CompareExchange(Int16, Int16, Int16)

比較兩個 16 位無符號整數是否相等,如果相等,則會取代第一個值。

CompareExchange(Double, Double, Double)

比較兩個雙精確度浮點數是否相等,如果相等,則會取代第一個值。

CompareExchange(Byte, Byte, Byte)

比較兩個 8 位無符號整數是否相等,如果相等,則會取代第一個值。

CompareExchange(IntPtr, IntPtr, IntPtr)

比較兩個平臺特定句柄或指標是否相等,如果相等,則會取代第一個句柄。

CompareExchange<T>(T, T, T)

比較指定之參考型別的兩個實例 T 參考相等,如果相等,則會取代第一個實例。

CompareExchange(UIntPtr, UIntPtr, UIntPtr)

來源:
Interlocked.cs
來源:
Interlocked.cs
來源:
Interlocked.cs

重要

此 API 不符合 CLS 規範。

比較兩個平臺特定句柄或指標是否相等,如果相等,則會取代第一個句柄。

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

參數

location1
UIntPtr

unativeint

目的地 UIntPtr,其值會與 comparand 的值進行比較,且可能由 value取代。

value
UIntPtr

unativeint

如果比較結果相等,則會取代目的地值的 UIntPtr

comparand
UIntPtr

unativeint

location1的值相比較的 UIntPtr

傳回

UIntPtr

unativeint

location1中的原始值。

屬性

例外狀況

location1 的位址是 null 指標。

適用於

CompareExchange(UInt64, UInt64, UInt64)

來源:
Interlocked.cs
來源:
Interlocked.cs
來源:
Interlocked.cs

重要

此 API 不符合 CLS 規範。

比較兩個 64 位無符號整數是否相等,如果相等,則會取代第一個值。

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

參數

location1
UInt64

目的地,其值會與 comparand 進行比較,並可能取代。

value
UInt64

如果比較結果相等,則取代目的值的值。

comparand
UInt64

location1值相比較的值。

傳回

location1中的原始值。

屬性

例外狀況

location1 的位址是 null 指標。

適用於

CompareExchange(UInt32, UInt32, UInt32)

來源:
Interlocked.cs
來源:
Interlocked.cs
來源:
Interlocked.cs

重要

此 API 不符合 CLS 規範。

比較兩個 32 位無符號整數是否相等,如果相等,則會取代第一個值。

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

參數

location1
UInt32

目的地,其值會與 comparand 進行比較,並可能取代。

value
UInt32

如果比較結果相等,則取代目的值的值。

comparand
UInt32

location1值相比較的值。

傳回

location1中的原始值。

屬性

例外狀況

location1 的位址是 null 指標。

適用於

CompareExchange(UInt16, UInt16, UInt16)

重要

此 API 不符合 CLS 規範。

比較兩個 16 位帶正負號的整數是否相等,如果相等,則會取代第一個值。

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

參數

location1
UInt16

目的地,其值會與 comparand 進行比較,並可能取代。

value
UInt16

如果比較結果相等,則取代目的值的值。

comparand
UInt16

location1值相比較的值。

傳回

location1中的原始值。

屬性

例外狀況

location1 的位址是 null 指標。

適用於

CompareExchange(Single, Single, Single)

來源:
Interlocked.cs
來源:
Interlocked.cs
來源:
Interlocked.cs

比較兩個單精度浮點數是否相等,如果相等,則會取代第一個值。

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

目的地,其值會與 comparand 進行比較,並可能取代。

value
Single

如果比較結果相等,則取代目的值的值。

comparand
Single

location1值相比較的值。

傳回

location1中的原始值。

例外狀況

location1 的位址是 null 指標。

範例

下列程式代碼範例示範線程安全方法,其會累積執行總 Single 值。 兩個線程會使用安全線程方法和一般加法,以及比較線程完成總計時,新增一系列 Single 值。 在雙處理器計算機上,總計有顯著差異。

在安全線程方法中,會儲存執行總計的初始值,然後使用 CompareExchange 方法,將新計算的總計與舊的總計交換。 如果傳回值不等於執行總計的已儲存值,則另一個線程會同時更新總計。 在此情況下,必須重複嘗試更新執行總數。

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

備註

如果 comparandlocation1 中的值相等,則 value 會儲存在 location1中。 否則,不會執行任何作業。 比較和交換作業會以不可部分完成的作業的形式執行。 CompareExchange 的傳回值是 location1中的原始值,不論交換是否進行。

另請參閱

適用於

CompareExchange(Object, Object, Object)

來源:
Interlocked.cs
來源:
Interlocked.cs
來源:
Interlocked.CoreCLR.cs

比較兩個對象的參考相等,如果相等,則會取代第一個物件。

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

參數

location1
Object

以傳址方式與 comparand 比較且可能取代的目的地物件。

value
Object

如果參考比較結果相等,則取代目的地對象的物件。

comparand
Object

location1上,參考 物件所比較的物件。

傳回

location1中的原始值。

例外狀況

location1 的位址是 null 指標。

備註

重要

從 .NET Framework 2.0 開始,CompareExchange<T>(T, T, T) 方法多載會提供參考型別的型別安全替代方案。 建議您呼叫它,而不是這個多載。

如果 comparandlocation1 中的物件依傳址方式相等,則 value 會儲存在 location1中。 否則,不會執行任何作業。 比較和交換作業會以不可部分完成的作業的形式執行。 CompareExchange 的傳回值是 location1中的原始值,不論交換是否進行。

注意

對象會比較參考相等,而不是值相等。 因此,相同實值型別 (例如整數 3) 的兩個 Boxed 實例一律不相等,而且不會執行任何作業。 請勿搭配實值型別使用此多載。

另請參閱

適用於

CompareExchange(SByte, SByte, SByte)

重要

此 API 不符合 CLS 規範。

比較兩個 8 位帶正負號的整數是否相等,如果相等,則會取代第一個值。

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

參數

location1
SByte

目的地,其值會與 comparand 進行比較,並可能取代。

value
SByte

如果比較結果相等,則取代目的值的值。

comparand
SByte

location1值相比較的值。

傳回

location1中的原始值。

屬性

例外狀況

location1 的位址是 null 指標。

適用於

CompareExchange(Int64, Int64, Int64)

來源:
Interlocked.cs
來源:
Interlocked.cs
來源:
Interlocked.CoreCLR.cs

比較兩個 64 位帶正負號的整數是否相等,如果相等,則會取代第一個值。

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

目的地,其值會與 comparand 進行比較,並可能取代。

value
Int64

如果比較結果相等,則取代目的值的值。

comparand
Int64

location1值相比較的值。

傳回

location1中的原始值。

例外狀況

location1 的位址是 null 指標。

備註

如果 comparandlocation1 中的值相等,則 value 會儲存在 location1中。 否則,不會執行任何作業。 比較和交換作業會以不可部分完成的作業的形式執行。 CompareExchange 的傳回值是 location1中的原始值,不論交換是否進行。

另請參閱

適用於

CompareExchange(Int32, Int32, Int32)

來源:
Interlocked.cs
來源:
Interlocked.cs
來源:
Interlocked.CoreCLR.cs

比較兩個 32 位帶正負號的整數是否相等,如果相等,則會取代第一個值。

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

目的地,其值會與 comparand 進行比較,並可能取代。

value
Int32

如果比較結果相等,則取代目的值的值。

comparand
Int32

location1值相比較的值。

傳回

location1中的原始值。

例外狀況

location1 的位址是 null 指標。

範例

下列程式代碼範例示範可累積執行總計的線程安全方法。 會儲存執行總計的初始值,然後使用 CompareExchange 方法,將新計算的總計與舊的總計交換。 如果傳回值不等於執行總計的已儲存值,則另一個線程會同時更新總計。 在此情況下,必須重複嘗試更新執行總數。

注意

在 .NET Framework 2.0 版中引進的 Add 方法,提供更方便的方式來累積整數的線程安全執行總計。

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

備註

如果 comparandlocation1 中的值相等,則 value 會儲存在 location1中。 否則,不會執行任何作業。 比較和交換作業會以不可部分完成的作業的形式執行。 CompareExchange 的傳回值是 location1中的原始值,不論交換是否進行。

另請參閱

適用於

CompareExchange(Int16, Int16, Int16)

比較兩個 16 位無符號整數是否相等,如果相等,則會取代第一個值。

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

參數

location1
Int16

目的地,其值會與 comparand 進行比較,並可能取代。

value
Int16

如果比較結果相等,則取代目的值的值。

comparand
Int16

location1值相比較的值。

傳回

location1中的原始值。

例外狀況

location1 的位址是 null 指標。

適用於

CompareExchange(Double, Double, Double)

來源:
Interlocked.cs
來源:
Interlocked.cs
來源:
Interlocked.cs

比較兩個雙精確度浮點數是否相等,如果相等,則會取代第一個值。

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

目的地,其值會與 comparand 進行比較,並可能取代。

value
Double

如果比較結果相等,則取代目的值的值。

comparand
Double

location1值相比較的值。

傳回

location1中的原始值。

例外狀況

location1 的位址是 null 指標。

範例

下列程式代碼範例示範線程安全方法,其會累積執行總 Double 值。 兩個線程會使用安全線程方法和一般加法,以及比較線程完成總計時,新增一系列 Double 值。 在雙處理器計算機上,總計有顯著差異。

在安全線程方法中,會儲存執行總計的初始值,然後使用 CompareExchange 方法,將新計算的總計與舊的總計交換。 如果傳回值不等於執行總計的已儲存值,則另一個線程會同時更新總計。 在此情況下,必須重複嘗試更新執行總數。

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

備註

如果 comparandlocation1 中的值相等,則 value 會儲存在 location1中。 否則,不會執行任何作業。 比較和交換作業會以不可部分完成的作業的形式執行。 CompareExchange 的傳回值是 location1中的原始值,不論交換是否進行。

另請參閱

適用於

CompareExchange(Byte, Byte, Byte)

比較兩個 8 位無符號整數是否相等,如果相等,則會取代第一個值。

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

參數

location1
Byte

目的地,其值會與 comparand 進行比較,並可能取代。

value
Byte

如果比較結果相等,則取代目的值的值。

comparand
Byte

location1值相比較的值。

傳回

location1中的原始值。

例外狀況

location1 的位址是 null 指標。

適用於

CompareExchange(IntPtr, IntPtr, IntPtr)

來源:
Interlocked.cs
來源:
Interlocked.cs
來源:
Interlocked.cs

比較兩個平臺特定句柄或指標是否相等,如果相等,則會取代第一個句柄。

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

nativeint

目的地 IntPtr,其值會與 comparand 的值進行比較,且可能由 value取代。

value
IntPtr

nativeint

如果比較結果相等,則會取代目的地值的 IntPtr

comparand
IntPtr

nativeint

location1的值相比較的 IntPtr

傳回

IntPtr

nativeint

location1中的原始值。

例外狀況

location1 的位址是 null 指標。

備註

如果 comparandlocation1 中的值相等,則 value 會儲存在 location1中。 否則,不會執行任何作業。 比較和交換作業會以不可部分完成的作業的形式執行。 這個方法的傳回值是 location1中的原始值,不論交換是否進行。

注意

IntPtr 是平臺特定的類型。

另請參閱

適用於

CompareExchange<T>(T, T, T)

來源:
Interlocked.CoreCLR.cs
來源:
Interlocked.CoreCLR.cs
來源:
Interlocked.CoreCLR.cs

比較指定之參考型別的兩個實例 T 參考相等,如果相等,則會取代第一個實例。

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

類型參數

T

要用於 location1valuecomparand的類型。 此類型必須是參考型別。

參數

location1
T

目的地,其值會以傳址方式與 comparand 進行比較,並可能取代。 這是參考參數(在 C# 中ref,在 Visual Basic 中 ByRef)。

value
T

如果以傳址方式比較結果相等,則取代目的值的值。

comparand
T

參考值與 location1的值比較的值。

傳回

T

location1中的原始值。

屬性

例外狀況

location1 的位址是 null 指標。

指定了不支援的 T

備註

如果 comparandlocation1 中的值依傳址方式相等,則 value 會儲存在 location1中。 否則,不會執行任何作業。 比較和交換會以不可部分完成的作業的形式執行。 這個方法的傳回值是 location1中的原始值,不論交換是否進行。

這個方法僅支持參考型別。 實值型別 Int32Int64IntPtrSingleDoubleCompareExchange 方法的多載,但不支援其他實值型別。

注意

此方法多載最好是 CompareExchange(Object, Object, Object) 方法多載,因為後者需要晚期存取目的地物件。

適用於