Interlocked.CompareExchange Methode

Definitie

Vergelijkt twee waarden voor gelijkheid en vervangt, als ze gelijk zijn, de eerste waarde als een atomische bewerking.

Overloads

Name Description
CompareExchange(Double, Double, Double)

Vergelijkt twee drijvendekommanummers met dubbele precisie voor gelijkheid en vervangt, als ze gelijk zijn, de eerste waarde als een atomische bewerking.

CompareExchange(Int32, Int32, Int32)

Vergelijkt twee 32-bits ondertekende gehele getallen voor gelijkheid en vervangt, als ze gelijk zijn, de eerste waarde als een atomische bewerking.

CompareExchange(Int64, Int64, Int64)

Vergelijkt twee 64-bits ondertekende gehele getallen voor gelijkheid en vervangt, als deze gelijk zijn, de eerste waarde als een atomische bewerking.

CompareExchange(IntPtr, IntPtr, IntPtr)

Vergelijkt twee met systeemeigen grootte ondertekende gehele getallen voor gelijkheid en vervangt, als ze gelijk zijn, de eerste als atomische bewerking.

CompareExchange(Object, Object, Object)

Vergelijkt twee objecten voor verwijzings gelijkheid en, als ze gelijk zijn, vervangt het eerste object als een atomische bewerking.

CompareExchange(Single, Single, Single)

Vergelijkt twee drijvendekommanummers met één precisie voor gelijkheid en vervangt, als ze gelijk zijn, de eerste waarde als een atomische bewerking.

CompareExchange<T>(T, T, T)

Vergelijkt twee exemplaren van het opgegeven type T voor verwijzings gelijkheid en, als ze gelijk zijn, vervangt de eerste als een atomische bewerking.

CompareExchange(Double, Double, Double)

Vergelijkt twee drijvendekommanummers met dubbele precisie voor gelijkheid en vervangt, als ze gelijk zijn, de eerste waarde als een atomische bewerking.

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

Parameters

location1
Double

De bestemming, waarvan de waarde wordt vergeleken met comparand en mogelijk vervangen.

value
Double

De waarde die de doelwaarde vervangt als de vergelijking resulteert in gelijkheid.

comparand
Double

De waarde die wordt vergeleken met de waarde op location1.

Retouren

De oorspronkelijke waarde in location1.

Uitzonderingen

Het adres van location1 is een null-aanwijzer.

Voorbeelden

In het volgende codevoorbeeld ziet u een threadveilige methode waarmee een actief totaal van Double waarden wordt verzameld. Twee threads voegen een reeks waarden toe met behulp van Double de thread-veilige methode en gewone toevoeging, en wanneer de threads de totalen voltooien, worden vergeleken. Op een computer met dubbele processor is er een aanzienlijk verschil in de totalen.

In de thread-safe-methode wordt de initiële waarde van het lopende totaal opgeslagen en vervolgens wordt de CompareExchange methode gebruikt om het zojuist berekende totaal in te wisselen met het oude totaal. Als de retourwaarde niet gelijk is aan de opgeslagen waarde van het lopende totaal, heeft een andere thread het totaal in de tussentijd bijgewerkt. In dat geval moet de poging om het voorlopig totaal bij te werken worden herhaald.

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

Opmerkingen

Als comparand en de waarde gelijk location1 zijn, wordt deze value opgeslagen in location1. Anders wordt er geen bewerking uitgevoerd. De vergelijkings- en uitwisselingsbewerkingen worden uitgevoerd als een atomische bewerking. De retourwaarde is CompareExchange de oorspronkelijke waarde in location1, ongeacht of de uitwisseling plaatsvindt.

Zie ook

Van toepassing op

CompareExchange(Int32, Int32, Int32)

Vergelijkt twee 32-bits ondertekende gehele getallen voor gelijkheid en vervangt, als ze gelijk zijn, de eerste waarde als een atomische bewerking.

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

Parameters

location1
Int32

De bestemming, waarvan de waarde wordt vergeleken met comparand en mogelijk vervangen.

value
Int32

De waarde die de doelwaarde vervangt als de vergelijking resulteert in gelijkheid.

comparand
Int32

De waarde die wordt vergeleken met de waarde op location1.

Retouren

De oorspronkelijke waarde in location1.

Uitzonderingen

Het adres van location1 is een null-aanwijzer.

Voorbeelden

In het volgende codevoorbeeld ziet u een threadveilige methode waarmee een voorlopig totaal wordt verzameld. De initiële waarde van het lopende totaal wordt opgeslagen en vervolgens wordt de CompareExchange methode gebruikt om het zojuist berekende totaal in te wisselen met het oude totaal. Als de retourwaarde niet gelijk is aan de opgeslagen waarde van het lopende totaal, heeft een andere thread het totaal in de tussentijd bijgewerkt. In dat geval moet de poging om het voorlopig totaal bij te werken worden herhaald.

Note

De Add methode biedt een handigere manier om thread-safe lopende totalen voor gehele getallen te verzamelen.

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

Opmerkingen

Als comparand en de waarde gelijk location1 zijn, wordt deze value opgeslagen in location1. Anders wordt er geen bewerking uitgevoerd. De vergelijkings- en uitwisselingsbewerkingen worden uitgevoerd als een atomische bewerking. De retourwaarde is CompareExchange de oorspronkelijke waarde in location1, ongeacht of de uitwisseling plaatsvindt.

Zie ook

Van toepassing op

CompareExchange(Int64, Int64, Int64)

Vergelijkt twee 64-bits ondertekende gehele getallen voor gelijkheid en vervangt, als deze gelijk zijn, de eerste waarde als een atomische bewerking.

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

Parameters

location1
Int64

De bestemming, waarvan de waarde wordt vergeleken met comparand en mogelijk vervangen.

value
Int64

De waarde die de doelwaarde vervangt als de vergelijking resulteert in gelijkheid.

comparand
Int64

De waarde die wordt vergeleken met de waarde op location1.

Retouren

De oorspronkelijke waarde in location1.

Uitzonderingen

Het adres van location1 is een null-aanwijzer.

Opmerkingen

Als comparand en de waarde gelijk location1 zijn, wordt deze value opgeslagen in location1. Anders wordt er geen bewerking uitgevoerd. De vergelijkings- en uitwisselingsbewerkingen worden uitgevoerd als een atomische bewerking. De retourwaarde is CompareExchange de oorspronkelijke waarde in location1, ongeacht of de uitwisseling plaatsvindt.

Zie ook

Van toepassing op

CompareExchange(IntPtr, IntPtr, IntPtr)

Vergelijkt twee met systeemeigen grootte ondertekende gehele getallen voor gelijkheid en vervangt, als ze gelijk zijn, de eerste als atomische bewerking.

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

Parameters

location1
IntPtr

nativeint

De bestemming, waarvan de waarde wordt vergeleken met de waarde van comparand en mogelijk vervangen door value.

value
IntPtr

nativeint

De waarde die de doelwaarde vervangt als de vergelijking resulteert in gelijkheid.

comparand
IntPtr

nativeint

De waarde die wordt vergeleken met de waarde op location1.

Retouren

IntPtr

nativeint

De oorspronkelijke waarde in location1.

Uitzonderingen

Het adres van location1 is een null-aanwijzer.

Opmerkingen

Als comparand en de waarde gelijk location1 zijn, wordt deze value opgeslagen in location1. Anders wordt er geen bewerking uitgevoerd. De vergelijkings- en uitwisselingsbewerkingen worden uitgevoerd als een atomische bewerking. De retourwaarde van deze methode is de oorspronkelijke waarde in location1, ongeacht of de uitwisseling plaatsvindt.

Note

IntPtr is een platformspecifiek type.

Zie ook

Van toepassing op

CompareExchange(Object, Object, Object)

Vergelijkt twee objecten voor verwijzings gelijkheid en, als ze gelijk zijn, vervangt het eerste object als een atomische bewerking.

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

Parameters

location1
Object

Het doelobject dat wordt vergeleken door verwijzing met comparand en mogelijk vervangen.

value
Object

Het object dat het doelobject vervangt als de verwijzingsvergelijking resulteert in gelijkheid.

comparand
Object

Het object dat wordt vergeleken met verwijzing naar het object op location1.

Retouren

De oorspronkelijke waarde in location1.

Uitzonderingen

Het adres van location1 is een null aanwijzer.

Opmerkingen

Important

De overbelasting van de CompareExchange<T>(T, T, T) methode biedt een algemeen alternatief dat kan worden gebruikt voor concrete referentietypen.

Als comparand en het object location1 gelijk zijn aan een verwijzing, wordt het value opgeslagen in location1. Anders wordt er geen bewerking uitgevoerd. De vergelijkings- en uitwisselingsbewerkingen worden uitgevoerd als een atomische bewerking. De retourwaarde is CompareExchange de oorspronkelijke waarde in location1, ongeacht of de uitwisseling plaatsvindt.

Note

De objecten worden vergeleken voor verwijzings gelijkheid in plaats van waarde gelijkheid. Als gevolg hiervan lijken twee boxed exemplaren van hetzelfde waardetype (bijvoorbeeld het gehele getal 3) altijd ongelijk te zijn en wordt er geen bewerking uitgevoerd. Gebruik deze overbelasting niet met waardetypen.

Zie ook

Van toepassing op

CompareExchange(Single, Single, Single)

Vergelijkt twee drijvendekommanummers met één precisie voor gelijkheid en vervangt, als ze gelijk zijn, de eerste waarde als een atomische bewerking.

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

Parameters

location1
Single

De bestemming, waarvan de waarde wordt vergeleken met comparand en mogelijk vervangen.

value
Single

De waarde die de doelwaarde vervangt als de vergelijking resulteert in gelijkheid.

comparand
Single

De waarde die wordt vergeleken met de waarde op location1.

Retouren

De oorspronkelijke waarde in location1.

Uitzonderingen

Het adres van location1 is een null-aanwijzer.

Voorbeelden

In het volgende codevoorbeeld ziet u een threadveilige methode waarmee een actief totaal van Single waarden wordt verzameld. Twee threads voegen een reeks waarden toe met behulp van Single de thread-veilige methode en gewone toevoeging, en wanneer de threads de totalen voltooien, worden vergeleken. Op een computer met dubbele processor is er een aanzienlijk verschil in de totalen.

In de thread-safe-methode wordt de initiële waarde van het lopende totaal opgeslagen en vervolgens wordt de CompareExchange methode gebruikt om het zojuist berekende totaal in te wisselen met het oude totaal. Als de retourwaarde niet gelijk is aan de opgeslagen waarde van het lopende totaal, heeft een andere thread het totaal in de tussentijd bijgewerkt. In dat geval moet de poging om het voorlopig totaal bij te werken worden herhaald.

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

Opmerkingen

Als comparand en de waarde gelijk location1 zijn, wordt deze value opgeslagen in location1. Anders wordt er geen bewerking uitgevoerd. De vergelijkings- en uitwisselingsbewerkingen worden uitgevoerd als een atomische bewerking. De retourwaarde is CompareExchange de oorspronkelijke waarde in location1, ongeacht of de uitwisseling plaatsvindt.

Zie ook

Van toepassing op

CompareExchange<T>(T, T, T)

Vergelijkt twee exemplaren van het opgegeven type T voor verwijzings gelijkheid en, als ze gelijk zijn, vervangt de eerste als een atomische bewerking.

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

Type parameters

T

Het type dat moet worden gebruikt voor location1, valueen comparand.

Parameters

location1
T

De bestemming, waarvan de waarde wordt vergeleken met verwijzing door comparand en mogelijk vervangen. Dit is een referentieparameter (ref in C#, ByRef in Visual Basic).

value
T

De waarde die de doelwaarde vervangt als de vergelijking door verwijzing resulteert in gelijkheid.

comparand
T

De waarde die wordt vergeleken met een verwijzing naar de waarde op location1.

Retouren

T

De oorspronkelijke waarde in location1.

Kenmerken

Uitzonderingen

Het adres van location1 is een null-aanwijzer.

Er wordt een niet-ondersteund T . In .NET 8 en eerdere versies moet T een verwijzingstype zijn. In .NET 9 en latere versies moet T een verwijzing, primitief of opsommingstype zijn.

Opmerkingen

Als comparand en de waarde gelijk zijn aan de referentie location1 , wordt deze value opgeslagen in location1. Anders wordt er geen bewerking uitgevoerd. De vergelijking en de uitwisseling worden uitgevoerd als een atomische bewerking. De retourwaarde van deze methode is de oorspronkelijke waarde in location1, ongeacht of de uitwisseling plaatsvindt.

Van toepassing op