Export (0) Print
Expand All
0 out of 1 rated this helpful - Rate this topic

Interlocked.CompareExchange Method

Compares two values for equality and, if they are equal, replaces one of the values.

Overload List

Compares two 32-bit signed integers for equality and, if they are equal, replaces one of the values.

Supported by the .NET Compact Framework.

[Visual Basic] Overloads Public Shared Function CompareExchange(ByRef Integer, Integer, Integer) As Integer
[C#] public static int CompareExchange(ref int, int, int);
[C++] public: static int CompareExchange(int*, int*, int*);
[JScript] public static function CompareExchange(int, int, int) : int;

Compares two objects for equality and, if they are equal, replaces one of the objects.

Supported by the .NET Compact Framework.

[Visual Basic] Overloads Public Shared Function CompareExchange(ByRef Object, Object, Object) As Object
[C#] public static object CompareExchange(ref object, object, object);
[C++] public: static Object* CompareExchange(Object**, Object**, Object**);
[JScript] public static function CompareExchange(Object, Object, Object) : Object;

Compares two single-precision floating point numbers for equality and, if they are equal, replaces one of the values.

[Visual Basic] Overloads Public Shared Function CompareExchange(ByRef Single, Single, Single) As Single
[C#] public static float CompareExchange(ref float, float, float);
[C++] public: static float CompareExchange(float*, float*, float*);
[JScript] public static function CompareExchange(float, float, float) : float;

Example

[Visual Basic, C#, C++] Note   This example shows how to use one of the overloaded versions of CompareExchange. For other examples that might be available, see the individual overload topics.
[Visual Basic] 
' 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

[C#] 
// 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;
    }
}

[C++] 
// 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 <mscorlib.dll>
#using <system.dll>

using namespace System::Threading;

public __gc class ThreadSafe 
{
    // totalValue contains a running total that can be updated
    // by multiple threads. It must be protected from unsynchronized 
    // access.
private:
    int totalValue;

    // The Total property returns the running total.
public:
    __property int get_Total()
    {
        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(&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;
    }
};

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

See Also

Interlocked Class | Interlocked Members | System.Threading Namespace

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.