Udostępnij za pośrednictwem


Interlocked.CompareExchange Metoda

Definicja

Porównuje dwie wartości równości i, jeśli są równe, zastępuje pierwszą wartość.

Przeciążenia

CompareExchange(UIntPtr, UIntPtr, UIntPtr)

Porównuje dwa uchwyty specyficzne dla platformy lub wskaźniki równości, a jeśli są równe, zastępuje pierwszy z nich.

CompareExchange(UInt64, UInt64, UInt64)

Porównuje dwie 64-bitowe liczby całkowite bez znaku dla równości, a jeśli są równe, zamienia pierwszą wartość.

CompareExchange(UInt32, UInt32, UInt32)

Porównuje dwie 32-bitowe liczby całkowite bez znaku dla równości, a jeśli są równe, zamienia pierwszą wartość.

CompareExchange(UInt16, UInt16, UInt16)

Porównuje dwie 16-bitowe liczby całkowite ze znakiem równości, a jeśli są równe, zastępuje pierwszą wartość.

CompareExchange(Single, Single, Single)

Porównuje dwie liczby zmiennoprzecinkowe o pojedynczej precyzji i, jeśli są równe, zamienia pierwszą wartość.

CompareExchange(Object, Object, Object)

Porównuje dwa obiekty pod kątem równości odwołań i, jeśli są równe, zastępuje pierwszy obiekt.

CompareExchange(SByte, SByte, SByte)

Porównuje dwie 8-bitowe liczby całkowite ze znakiem równości, a jeśli są równe, zastępuje pierwszą wartość.

CompareExchange(Int64, Int64, Int64)

Porównuje dwie 64-bitowe liczby całkowite ze znakiem równości, a jeśli są równe, zastępuje pierwszą wartość.

CompareExchange(Int32, Int32, Int32)

Porównuje dwie 32-bitowe liczby całkowite ze znakiem równości, a jeśli są równe, zastępuje pierwszą wartość.

CompareExchange(Int16, Int16, Int16)

Porównuje dwie 16-bitowe liczby całkowite bez znaku dla równości i, jeśli są równe, zamienia pierwszą wartość.

CompareExchange(Double, Double, Double)

Porównuje dwie liczby zmiennoprzecinkowe o podwójnej precyzji i, jeśli są równe, zamienia pierwszą wartość.

CompareExchange(Byte, Byte, Byte)

Porównuje dwie 8-bitowe liczby całkowite bez znaku dla równości, a jeśli są równe, zamienia pierwszą wartość.

CompareExchange(IntPtr, IntPtr, IntPtr)

Porównuje dwa uchwyty specyficzne dla platformy lub wskaźniki równości, a jeśli są równe, zastępuje pierwszy z nich.

CompareExchange<T>(T, T, T)

Porównuje dwa wystąpienia określonego typu odwołania T równości odwołań i, jeśli są równe, zastępuje pierwszy z nich.

CompareExchange(UIntPtr, UIntPtr, UIntPtr)

Źródło:
Interlocked.cs
Źródło:
Interlocked.cs
Źródło:
Interlocked.cs

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Porównuje dwa uchwyty specyficzne dla platformy lub wskaźniki równości, a jeśli są równe, zastępuje pierwszy z nich.

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

Parametry

location1
UIntPtr

unativeint

Docelowy UIntPtr, którego wartość jest porównywana z wartością comparand i prawdopodobnie zastąpiona przez value.

value
UIntPtr

unativeint

UIntPtr, który zastępuje wartość docelową, jeśli porównanie powoduje równość.

comparand
UIntPtr

unativeint

UIntPtr, który jest porównywany z wartością w location1.

Zwraca

UIntPtr

unativeint

Oryginalna wartość w location1.

Atrybuty

Wyjątki

Adres location1 jest wskaźnikiem null.

Dotyczy

CompareExchange(UInt64, UInt64, UInt64)

Źródło:
Interlocked.cs
Źródło:
Interlocked.cs
Źródło:
Interlocked.cs

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Porównuje dwie 64-bitowe liczby całkowite bez znaku dla równości, a jeśli są równe, zamienia pierwszą wartość.

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

Parametry

location1
UInt64

Miejsce docelowe, którego wartość jest porównywana z comparand i ewentualnie zamieniona.

value
UInt64

Wartość, która zastępuje wartość docelową, jeśli porównanie powoduje równość.

comparand
UInt64

Wartość, która jest porównywana z wartością w location1.

Zwraca

Oryginalna wartość w location1.

Atrybuty

Wyjątki

Adres location1 jest wskaźnikiem null.

Dotyczy

CompareExchange(UInt32, UInt32, UInt32)

Źródło:
Interlocked.cs
Źródło:
Interlocked.cs
Źródło:
Interlocked.cs

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Porównuje dwie 32-bitowe liczby całkowite bez znaku dla równości, a jeśli są równe, zamienia pierwszą wartość.

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

Parametry

location1
UInt32

Miejsce docelowe, którego wartość jest porównywana z comparand i ewentualnie zamieniona.

value
UInt32

Wartość, która zastępuje wartość docelową, jeśli porównanie powoduje równość.

comparand
UInt32

Wartość, która jest porównywana z wartością w location1.

Zwraca

Oryginalna wartość w location1.

Atrybuty

Wyjątki

Adres location1 jest wskaźnikiem null.

Dotyczy

CompareExchange(UInt16, UInt16, UInt16)

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Porównuje dwie 16-bitowe liczby całkowite ze znakiem równości, a jeśli są równe, zastępuje pierwszą wartość.

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

Parametry

location1
UInt16

Miejsce docelowe, którego wartość jest porównywana z comparand i ewentualnie zamieniona.

value
UInt16

Wartość, która zastępuje wartość docelową, jeśli porównanie powoduje równość.

comparand
UInt16

Wartość, która jest porównywana z wartością w location1.

Zwraca

Oryginalna wartość w location1.

Atrybuty

Wyjątki

Adres location1 jest wskaźnikiem null.

Dotyczy

CompareExchange(Single, Single, Single)

Źródło:
Interlocked.cs
Źródło:
Interlocked.cs
Źródło:
Interlocked.cs

Porównuje dwie liczby zmiennoprzecinkowe o pojedynczej precyzji i, jeśli są równe, zamienia pierwszą wartość.

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

Parametry

location1
Single

Miejsce docelowe, którego wartość jest porównywana z comparand i ewentualnie zamieniona.

value
Single

Wartość, która zastępuje wartość docelową, jeśli porównanie powoduje równość.

comparand
Single

Wartość, która jest porównywana z wartością w location1.

Zwraca

Oryginalna wartość w location1.

Wyjątki

Adres location1 jest wskaźnikiem o wartości null.

Przykłady

Poniższy przykład kodu przedstawia metodę bezpieczną wątkowo, która gromadzi sumę bieżącą Single wartości. Dwa wątki dodają serię Single wartości przy użyciu metody bezpiecznego wątkowo i zwykłego dodawania, a gdy wątki zakończą sumę. Na komputerze z dwoma procesorami istnieje znacząca różnica w sumach.

W metodzie bezpiecznego wątkowo początkowa wartość sumy bieżącej jest zapisywana, a następnie metoda CompareExchange jest używana do wymiany nowo obliczonej sumy ze starą sumą. Jeśli wartość zwracana nie jest równa zapisanej wartości sumy bieżącej, inny wątek zaktualizował sumę w międzyczasie. W takim przypadku próba zaktualizowania sumy bieżącej musi zostać powtórzona.

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

Uwagi

Jeśli comparand i wartość w location1 są równe, value jest przechowywany w location1. W przeciwnym razie nie jest wykonywana żadna operacja. Operacje porównania i wymiany są wykonywane jako operacja niepodzielna. Wartość zwracana CompareExchange jest oryginalną wartością w location1, niezależnie od tego, czy wymiana ma miejsce.

Zobacz też

Dotyczy

CompareExchange(Object, Object, Object)

Źródło:
Interlocked.cs
Źródło:
Interlocked.cs
Źródło:
Interlocked.CoreCLR.cs

Porównuje dwa obiekty pod kątem równości odwołań i, jeśli są równe, zastępuje pierwszy obiekt.

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

Parametry

location1
Object

Obiekt docelowy, który jest porównywany przez odwołanie do comparand i ewentualnie zastąpiony.

value
Object

Obiekt, który zastępuje obiekt docelowy, jeśli porównanie odwołań powoduje równość.

comparand
Object

Obiekt, który jest porównywany przez odwołanie do obiektu w location1.

Zwraca

Oryginalna wartość w location1.

Wyjątki

Adres location1 jest wskaźnikiem null.

Uwagi

Ważny

Począwszy od programu .NET Framework 2.0, przeciążenie metody CompareExchange<T>(T, T, T) zapewnia bezpieczną alternatywę dla typów referencyjnych. Zalecamy wywołanie go zamiast tego przeciążenia.

Jeśli comparand i obiekt w location1 są równe przez odwołanie, value jest przechowywany w location1. W przeciwnym razie nie jest wykonywana żadna operacja. Operacje porównania i wymiany są wykonywane jako operacja niepodzielna. Wartość zwracana CompareExchange jest oryginalną wartością w location1, niezależnie od tego, czy wymiana ma miejsce.

Nuta

Obiekty są porównywane pod kątem równości odwołań, a nie równości wartości. W rezultacie dwa boxed wystąpienia tego samego typu wartości (na przykład liczba całkowita 3) zawsze wydają się być nierówne i nie jest wykonywana żadna operacja. Nie używaj tego przeciążenia z typami wartości.

Zobacz też

Dotyczy

CompareExchange(SByte, SByte, SByte)

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Porównuje dwie 8-bitowe liczby całkowite ze znakiem równości, a jeśli są równe, zastępuje pierwszą wartość.

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

Parametry

location1
SByte

Miejsce docelowe, którego wartość jest porównywana z comparand i ewentualnie zamieniona.

value
SByte

Wartość, która zastępuje wartość docelową, jeśli porównanie powoduje równość.

comparand
SByte

Wartość, która jest porównywana z wartością w location1.

Zwraca

Oryginalna wartość w location1.

Atrybuty

Wyjątki

Adres location1 jest wskaźnikiem null.

Dotyczy

CompareExchange(Int64, Int64, Int64)

Źródło:
Interlocked.cs
Źródło:
Interlocked.cs
Źródło:
Interlocked.CoreCLR.cs

Porównuje dwie 64-bitowe liczby całkowite ze znakiem równości, a jeśli są równe, zastępuje pierwszą wartość.

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

Parametry

location1
Int64

Miejsce docelowe, którego wartość jest porównywana z comparand i ewentualnie zamieniona.

value
Int64

Wartość, która zastępuje wartość docelową, jeśli porównanie powoduje równość.

comparand
Int64

Wartość, która jest porównywana z wartością w location1.

Zwraca

Oryginalna wartość w location1.

Wyjątki

Adres location1 jest wskaźnikiem o wartości null.

Uwagi

Jeśli comparand i wartość w location1 są równe, value jest przechowywany w location1. W przeciwnym razie nie jest wykonywana żadna operacja. Operacje porównania i wymiany są wykonywane jako operacja niepodzielna. Wartość zwracana CompareExchange jest oryginalną wartością w location1, niezależnie od tego, czy wymiana ma miejsce.

Zobacz też

Dotyczy

CompareExchange(Int32, Int32, Int32)

Źródło:
Interlocked.cs
Źródło:
Interlocked.cs
Źródło:
Interlocked.CoreCLR.cs

Porównuje dwie 32-bitowe liczby całkowite ze znakiem równości, a jeśli są równe, zastępuje pierwszą wartość.

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

Parametry

location1
Int32

Miejsce docelowe, którego wartość jest porównywana z comparand i ewentualnie zamieniona.

value
Int32

Wartość, która zastępuje wartość docelową, jeśli porównanie powoduje równość.

comparand
Int32

Wartość, która jest porównywana z wartością w location1.

Zwraca

Oryginalna wartość w location1.

Wyjątki

Adres location1 jest wskaźnikiem o wartości null.

Przykłady

W poniższym przykładzie kodu pokazano metodę bezpieczną wątkowo, która gromadzi sumę bieżącą. Początkowa wartość sumy bieżącej jest zapisywana, a następnie metoda CompareExchange jest używana do wymiany nowo obliczonej sumy ze starą sumą. Jeśli wartość zwracana nie jest równa zapisanej wartości sumy bieżącej, inny wątek zaktualizował sumę w międzyczasie. W takim przypadku próba zaktualizowania sumy bieżącej musi zostać powtórzona.

Nuta

Metoda Add, wprowadzona w wersji 2.0 programu .NET Framework, zapewnia wygodniejszy sposób gromadzenia sum działających bezpiecznie wątkowo dla liczb całkowitych.

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

Uwagi

Jeśli comparand i wartość w location1 są równe, value jest przechowywany w location1. W przeciwnym razie nie jest wykonywana żadna operacja. Operacje porównania i wymiany są wykonywane jako operacja niepodzielna. Wartość zwracana CompareExchange jest oryginalną wartością w location1, niezależnie od tego, czy wymiana ma miejsce.

Zobacz też

Dotyczy

CompareExchange(Int16, Int16, Int16)

Porównuje dwie 16-bitowe liczby całkowite bez znaku dla równości i, jeśli są równe, zamienia pierwszą wartość.

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

Parametry

location1
Int16

Miejsce docelowe, którego wartość jest porównywana z comparand i ewentualnie zamieniona.

value
Int16

Wartość, która zastępuje wartość docelową, jeśli porównanie powoduje równość.

comparand
Int16

Wartość, która jest porównywana z wartością w location1.

Zwraca

Oryginalna wartość w location1.

Wyjątki

Adres location1 jest wskaźnikiem null.

Dotyczy

CompareExchange(Double, Double, Double)

Źródło:
Interlocked.cs
Źródło:
Interlocked.cs
Źródło:
Interlocked.cs

Porównuje dwie liczby zmiennoprzecinkowe o podwójnej precyzji i, jeśli są równe, zamienia pierwszą wartość.

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

Parametry

location1
Double

Miejsce docelowe, którego wartość jest porównywana z comparand i ewentualnie zamieniona.

value
Double

Wartość, która zastępuje wartość docelową, jeśli porównanie powoduje równość.

comparand
Double

Wartość, która jest porównywana z wartością w location1.

Zwraca

Oryginalna wartość w location1.

Wyjątki

Adres location1 jest wskaźnikiem o wartości null.

Przykłady

Poniższy przykład kodu przedstawia metodę bezpieczną wątkowo, która gromadzi sumę bieżącą Double wartości. Dwa wątki dodają serię Double wartości przy użyciu metody bezpiecznego wątkowo i zwykłego dodawania, a gdy wątki zakończą sumę. Na komputerze z dwoma procesorami istnieje znacząca różnica w sumach.

W metodzie bezpiecznego wątkowo początkowa wartość sumy bieżącej jest zapisywana, a następnie metoda CompareExchange jest używana do wymiany nowo obliczonej sumy ze starą sumą. Jeśli wartość zwracana nie jest równa zapisanej wartości sumy bieżącej, inny wątek zaktualizował sumę w międzyczasie. W takim przypadku próba zaktualizowania sumy bieżącej musi zostać powtórzona.

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

Uwagi

Jeśli comparand i wartość w location1 są równe, value jest przechowywany w location1. W przeciwnym razie nie jest wykonywana żadna operacja. Operacje porównania i wymiany są wykonywane jako operacja niepodzielna. Wartość zwracana CompareExchange jest oryginalną wartością w location1, niezależnie od tego, czy wymiana ma miejsce.

Zobacz też

Dotyczy

CompareExchange(Byte, Byte, Byte)

Porównuje dwie 8-bitowe liczby całkowite bez znaku dla równości, a jeśli są równe, zamienia pierwszą wartość.

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

Parametry

location1
Byte

Miejsce docelowe, którego wartość jest porównywana z comparand i ewentualnie zamieniona.

value
Byte

Wartość, która zastępuje wartość docelową, jeśli porównanie powoduje równość.

comparand
Byte

Wartość, która jest porównywana z wartością w location1.

Zwraca

Oryginalna wartość w location1.

Wyjątki

Adres location1 jest wskaźnikiem null.

Dotyczy

CompareExchange(IntPtr, IntPtr, IntPtr)

Źródło:
Interlocked.cs
Źródło:
Interlocked.cs
Źródło:
Interlocked.cs

Porównuje dwa uchwyty specyficzne dla platformy lub wskaźniki równości, a jeśli są równe, zastępuje pierwszy z nich.

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

Parametry

location1
IntPtr

nativeint

Docelowy IntPtr, którego wartość jest porównywana z wartością comparand i prawdopodobnie zastąpiona przez value.

value
IntPtr

nativeint

IntPtr, który zastępuje wartość docelową, jeśli porównanie powoduje równość.

comparand
IntPtr

nativeint

IntPtr, który jest porównywany z wartością w location1.

Zwraca

IntPtr

nativeint

Oryginalna wartość w location1.

Wyjątki

Adres location1 jest wskaźnikiem o wartości null.

Uwagi

Jeśli comparand i wartość w location1 są równe, value jest przechowywany w location1. W przeciwnym razie nie jest wykonywana żadna operacja. Operacje porównania i wymiany są wykonywane jako operacja niepodzielna. Zwracana wartość tej metody jest oryginalną wartością w location1, niezależnie od tego, czy wymiana ma miejsce.

Nuta

IntPtr jest typem specyficznym dla platformy.

Zobacz też

Dotyczy

CompareExchange<T>(T, T, T)

Źródło:
Interlocked.CoreCLR.cs
Źródło:
Interlocked.CoreCLR.cs
Źródło:
Interlocked.CoreCLR.cs

Porównuje dwa wystąpienia określonego typu odwołania T równości odwołań i, jeśli są równe, zastępuje pierwszy z nich.

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

Parametry typu

T

Typ, który ma być używany dla location1, valuei comparand. Ten typ musi być typem odwołania.

Parametry

location1
T

Miejsce docelowe, którego wartość jest porównywana przez odwołanie do comparand i ewentualnie zastąpiona. Jest to parametr referencyjny (ref w języku C#, ByRef w Visual Basic).

value
T

Wartość, która zastępuje wartość docelową, jeśli porównanie przez odwołanie powoduje równość.

comparand
T

Wartość, która jest porównywana przez odwołanie do wartości w location1.

Zwraca

T

Oryginalna wartość w location1.

Atrybuty

Wyjątki

Adres location1 jest wskaźnikiem o wartości null.

Określono nieobsługiwany T.

Uwagi

Jeśli comparand i wartość w location1 są równe przez odwołanie, value jest przechowywany w location1. W przeciwnym razie nie jest wykonywana żadna operacja. Porównanie i wymiana są wykonywane jako operacja niepodzielna. Zwracana wartość tej metody jest oryginalną wartością w location1, niezależnie od tego, czy wymiana ma miejsce.

Ta metoda obsługuje tylko typy referencyjne. Istnieją przeciążenia metody CompareExchange dla typów wartości Int32, Int64, IntPtr, Singlei Double, ale nie ma obsługi innych typów wartości.

Nuta

To przeciążenie metody jest preferowane do przeciążenia metody CompareExchange(Object, Object, Object), ponieważ ten ostatni wymaga, aby obiekt docelowy był dostępny pod koniec ograniczenia.

Dotyczy