Export (0) Print
Expand All

Interlocked.CompareExchange Method (Int32, Int32, Int32)

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

Namespace: System.Threading
Assembly: mscorlib (in mscorlib.dll)

public static int CompareExchange (
	ref int location1,
	int value,
	int comparand
)
public static int CompareExchange (
	/** @ref */ int location1, 
	int value, 
	int comparand
)
Not applicable.

Parameters

location1

The destination, whose value is compared with comparand and possibly replaced.

value

The value that replaces the destination value if the comparison results in equality.

comparand

The value that is compared to the value at location1.

Return Value

The original value in location1.

Exception typeCondition

NullReferenceException

The address of location1 is a null pointer.

If comparand and the value in location1 are equal, then value is stored in location1. Otherwise, no operation is performed. The compare and exchange operations are performed as an atomic operation. The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.

The following code example demonstrates a thread-safe method that accumulates a running total. The initial value of the running total is saved, and then the CompareExchange method is used to exchange the newly computed total with the old total. If the return value is not equal to the saved value of the running total, then another thread has updated the total in the meantime. In that case, the attempt to update the running total must be repeated.

NoteNote:

The Add method, introduced in version 2.0 of the .NET Framework, provides a more convenient way to accumulate thread-safe running totals for integers.

// 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.
import 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.
    /** @property
     */
    public int get_Total()
    {
        return totalValue;
    } //get_Total

    // 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;
        } while (initialValue != Interlocked.CompareExchange(totalValue, 
            computedValue, initialValue));

        // 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.
        // 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;
    } //AddToTotal
} //ThreadSafe

Windows 98, Windows Server 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0

Community Additions

ADD
Show:
© 2014 Microsoft