Interlocked.CompareExchange Metod

Definition

Jämför två värden för likhet och ersätter, om de är lika med, det första värdet som en atomisk åtgärd.

Överlagringar

Name Description
CompareExchange(Double, Double, Double)

Jämför två flyttalsnummer med dubbel precision för likhet och ersätter, om de är lika med, det första värdet som en atomisk åtgärd.

CompareExchange(Int32, Int32, Int32)

Jämför två 32-bitars signerade heltal för likhet och ersätter, om de är lika med, det första värdet som en atomisk åtgärd.

CompareExchange(Int64, Int64, Int64)

Jämför två 64-bitars signerade heltal för likhet och ersätter, om de är lika med, det första värdet som en atomisk åtgärd.

CompareExchange(IntPtr, IntPtr, IntPtr)

Jämför två signerade heltal i intern storlek för likhet och ersätter, om de är lika, den första som en atomisk åtgärd.

CompareExchange(Object, Object, Object)

Jämför två objekt för referensjämlikhet och ersätter, om de är lika med, det första objektet som en atomisk åtgärd.

CompareExchange(Single, Single, Single)

Jämför två flyttalsnummer med enkel precision för likhet och ersätter, om de är lika med, det första värdet som en atomisk åtgärd.

CompareExchange<T>(T, T, T)

Jämför två instanser av den angivna typen T för referensjämlikhet och ersätter, om de är lika, den första som en atomisk åtgärd.

CompareExchange(Double, Double, Double)

Jämför två flyttalsnummer med dubbel precision för likhet och ersätter, om de är lika med, det första värdet som en atomisk åtgärd.

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

Parametrar

location1
Double

Målet, vars värde jämförs med comparand och eventuellt ersätts.

value
Double

Värdet som ersätter målvärdet om jämförelsen resulterar i likhet.

comparand
Double

Värdet som jämförs med värdet på location1.

Returer

Det ursprungliga värdet i location1.

Undantag

Adressen till location1 är en null-pekare.

Exempel

I följande kodexempel visas en trådsäker metod som ackumulerar en löpande summa av Double värden. Två trådar lägger till en serie värden med hjälp av Double den trådsäkra metoden och vanlig addition, och när trådarna slutförs jämförs summorna. På en dator med dubbla processorer finns det en betydande skillnad i summorna.

I den trådsäkra metoden sparas det ursprungliga värdet för den löpande summan och sedan CompareExchange används metoden för att byta ut den nyligen beräknade summan med den gamla summan. Om returvärdet inte är lika med det sparade värdet för den löpande summan har en annan tråd uppdaterat summan under tiden. I så fall måste försöket att uppdatera den löpande summan upprepas.

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

Kommentarer

Om comparand och värdet i location1 är lika med lagras det value i location1. Annars utförs ingen åtgärd. Jämförelse- och utbytesåtgärderna utförs som en atomisk åtgärd. Returvärdet CompareExchange för är det ursprungliga värdet i location1, oavsett om utbytet sker eller inte.

Se även

Gäller för

CompareExchange(Int32, Int32, Int32)

Jämför två 32-bitars signerade heltal för likhet och ersätter, om de är lika med, det första värdet som en atomisk åtgärd.

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

Parametrar

location1
Int32

Målet, vars värde jämförs med comparand och eventuellt ersätts.

value
Int32

Värdet som ersätter målvärdet om jämförelsen resulterar i likhet.

comparand
Int32

Värdet som jämförs med värdet på location1.

Returer

Det ursprungliga värdet i location1.

Undantag

Adressen till location1 är en null-pekare.

Exempel

I följande kodexempel visas en trådsäker metod som ackumulerar en löpande summa. Det initiala värdet för den löpande summan sparas och sedan CompareExchange används metoden för att utbyta den nyligen beräknade summan med den gamla summan. Om returvärdet inte är lika med det sparade värdet för den löpande summan har en annan tråd uppdaterat summan under tiden. I så fall måste försöket att uppdatera den löpande summan upprepas.

Note

Metoden Add ger ett bekvämare sätt att ackumulera trådsäkra löpande summor för heltal.

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

Kommentarer

Om comparand och värdet i location1 är lika med lagras det value i location1. Annars utförs ingen åtgärd. Jämförelse- och utbytesåtgärderna utförs som en atomisk åtgärd. Returvärdet CompareExchange för är det ursprungliga värdet i location1, oavsett om utbytet sker eller inte.

Se även

Gäller för

CompareExchange(Int64, Int64, Int64)

Jämför två 64-bitars signerade heltal för likhet och ersätter, om de är lika med, det första värdet som en atomisk åtgärd.

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

Parametrar

location1
Int64

Målet, vars värde jämförs med comparand och eventuellt ersätts.

value
Int64

Värdet som ersätter målvärdet om jämförelsen resulterar i likhet.

comparand
Int64

Värdet som jämförs med värdet på location1.

Returer

Det ursprungliga värdet i location1.

Undantag

Adressen till location1 är en null-pekare.

Kommentarer

Om comparand och värdet i location1 är lika med lagras det value i location1. Annars utförs ingen åtgärd. Jämförelse- och utbytesåtgärderna utförs som en atomisk åtgärd. Returvärdet CompareExchange för är det ursprungliga värdet i location1, oavsett om utbytet sker eller inte.

Se även

Gäller för

CompareExchange(IntPtr, IntPtr, IntPtr)

Jämför två signerade heltal i intern storlek för likhet och ersätter, om de är lika, den första som en atomisk åtgärd.

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

Parametrar

location1
IntPtr

nativeint

Målet, vars värde jämförs med värdet comparand för och eventuellt ersätts av value.

value
IntPtr

nativeint

Värdet som ersätter målvärdet om jämförelsen resulterar i likhet.

comparand
IntPtr

nativeint

Värdet som jämförs med värdet på location1.

Returer

IntPtr

nativeint

Det ursprungliga värdet i location1.

Undantag

Adressen till location1 är en null-pekare.

Kommentarer

Om comparand och värdet i location1 är lika med lagras det value i location1. Annars utförs ingen åtgärd. Jämförelse- och utbytesåtgärderna utförs som en atomisk åtgärd. Returvärdet för den här metoden är det ursprungliga värdet i location1, oavsett om utbytet sker eller inte.

Note

IntPtr är en plattformsspecifik typ.

Se även

Gäller för

CompareExchange(Object, Object, Object)

Jämför två objekt för referensjämlikhet och ersätter, om de är lika med, det första objektet som en atomisk åtgärd.

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

Parametrar

location1
Object

Målobjektet som jämförs med referens med comparand och eventuellt ersätts.

value
Object

Objektet som ersätter målobjektet om referensjämförelsen resulterar i likhet.

comparand
Object

Objektet som jämförs med objektet på location1.

Returer

Det ursprungliga värdet i location1.

Undantag

Adressen location1 till är en null pekare.

Kommentarer

Important

Metodöverlagringen CompareExchange<T>(T, T, T) är ett allmänt alternativ som kan användas för konkreta referenstyper.

Om comparand och -objektet i location1 är lika med referens lagras det value i location1. Annars utförs ingen åtgärd. Jämförelse- och utbytesåtgärderna utförs som en atomisk åtgärd. Returvärdet CompareExchange för är det ursprungliga värdet i location1, oavsett om utbytet sker eller inte.

Note

Objekten jämförs för referensjämlikhet snarare än värdejämlikhet. Därför verkar två boxade instanser av samma värdetyp (till exempel heltal 3) alltid vara ojämlika och ingen åtgärd utförs. Använd inte den här överlagringen med värdetyper.

Se även

Gäller för

CompareExchange(Single, Single, Single)

Jämför två flyttalsnummer med enkel precision för likhet och ersätter, om de är lika med, det första värdet som en atomisk åtgärd.

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

Parametrar

location1
Single

Målet, vars värde jämförs med comparand och eventuellt ersätts.

value
Single

Värdet som ersätter målvärdet om jämförelsen resulterar i likhet.

comparand
Single

Värdet som jämförs med värdet på location1.

Returer

Det ursprungliga värdet i location1.

Undantag

Adressen till location1 är en null-pekare.

Exempel

I följande kodexempel visas en trådsäker metod som ackumulerar en löpande summa av Single värden. Två trådar lägger till en serie värden med hjälp av Single den trådsäkra metoden och vanlig addition, och när trådarna slutförs jämförs summorna. På en dator med dubbla processorer finns det en betydande skillnad i summorna.

I den trådsäkra metoden sparas det ursprungliga värdet för den löpande summan och sedan CompareExchange används metoden för att byta ut den nyligen beräknade summan med den gamla summan. Om returvärdet inte är lika med det sparade värdet för den löpande summan har en annan tråd uppdaterat summan under tiden. I så fall måste försöket att uppdatera den löpande summan upprepas.

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

Kommentarer

Om comparand och värdet i location1 är lika med lagras det value i location1. Annars utförs ingen åtgärd. Jämförelse- och utbytesåtgärderna utförs som en atomisk åtgärd. Returvärdet CompareExchange för är det ursprungliga värdet i location1, oavsett om utbytet sker eller inte.

Se även

Gäller för

CompareExchange<T>(T, T, T)

Jämför två instanser av den angivna typen T för referensjämlikhet och ersätter, om de är lika, den första som en atomisk åtgärd.

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

Typparametrar

T

Den typ som ska användas för location1, valueoch comparand.

Parametrar

location1
T

Målet, vars värde jämförs med referens och comparand eventuellt ersätts. Det här är en referensparameter (ref i C#, ByRef i Visual Basic).

value
T

Värdet som ersätter målvärdet om jämförelsen med referens resulterar i likhet.

comparand
T

Värdet som jämförs med värdet vid location1.

Returer

T

Det ursprungliga värdet i location1.

Attribut

Undantag

Adressen till location1 är en null-pekare.

En som inte stöds har angetts T . I .NET 8 och tidigare versioner måste T vara en referenstyp. I .NET 9 och senare versioner måste T vara en referens, primitiv eller uppräkningstyp.

Kommentarer

Om comparand och värdet i location1 är lika med referens lagras det value i location1. Annars utförs ingen åtgärd. Jämförelsen och utbytet utförs som en atomisk åtgärd. Returvärdet för den här metoden är det ursprungliga värdet i location1, oavsett om utbytet sker eller inte.

Gäller för