Interlocked.Exchange Method

Definition

Sets a variable to a specified value as an atomic operation.

Overloads

Exchange(Single, Single)

Sets a single-precision floating point number to a specified value and returns the original value, as an atomic operation.

Exchange(Object, Object)

Sets an object to a specified value and returns a reference to the original object, as an atomic operation.

Exchange(IntPtr, IntPtr)

Sets a platform-specific handle or pointer to a specified value and returns the original value, as an atomic operation.

Exchange(Double, Double)

Sets a double-precision floating point number to a specified value and returns the original value, as an atomic operation.

Exchange(Int32, Int32)

Sets a 32-bit signed integer to a specified value and returns the original value, as an atomic operation.

Exchange(Int64, Int64)

Sets a 64-bit signed integer to a specified value and returns the original value, as an atomic operation.

Exchange<T>(T, T)

Sets a variable of the specified type T to a specified value and returns the original value, as an atomic operation.

Exchange(Single, Single)

Sets a single-precision floating point number to a specified value and returns the original value, as an atomic operation.

public static float Exchange (ref float location1, float value);
Parameters
location1
Single

The variable to set to the specified value.

value
Single

The value to which the location1 parameter is set.

Returns

The original value of location1.

Exceptions

The address of location1 is a null pointer.

Exchange(Object, Object)

Sets an object to a specified value and returns a reference to the original object, as an atomic operation.

public static object Exchange (ref object location1, object value);
Parameters
location1
Object

The variable to set to the specified value.

value
Object

The value to which the location1 parameter is set.

Returns

The original value of location1.

Exceptions

The address of location1 is a null pointer.

Examples

The following code example shows the syntax for using Exchange with any reference type object.

using namespace System;
using namespace System::Threading;
ref class AtomicExchange
{
private:
   ref class SomeType{};


   // To use Interlocked::Exchange, someType1 
   // must be declared as type Object*.
   Object^ someType1;
   SomeType^ someType2;

public:
   AtomicExchange()
   {
      someType1 = gcnew SomeType;
      someType2 = gcnew SomeType;
   }

   void Switch()
   {
      someType2 = dynamic_cast<SomeType^>(Interlocked::Exchange( someType1, dynamic_cast<Object^>(someType2) ));
   }

};

int main()
{
   AtomicExchange^ atomicExchange = gcnew AtomicExchange;
   Thread^ firstThread = gcnew Thread( gcnew ThreadStart( atomicExchange, &AtomicExchange::Switch ) );
   firstThread->Start();
}

using System;
using System.Threading;

class AtomicTest
{
    static void Main()
    {
        AtomicExchange atomicExchange = new AtomicExchange();
        Thread firstThread = 
            new Thread(new ThreadStart(atomicExchange.Switch));
        firstThread.Start();
    }
}

class AtomicExchange
{
    class SomeType{}

    // To use Interlocked.Exchange, someType1 
    // must be declared as type Object.
    object   someType1;
    SomeType someType2;

    public AtomicExchange() 
    {
        someType1 = new SomeType();
        someType2 = new SomeType();
    }

    public void Switch()
    {
        someType2 = (SomeType)Interlocked.Exchange(
            ref someType1, (object)someType2);
    }
}
Imports System
Imports System.Threading

Public Class AtomicTest

    <MTAThread> _
    Shared Sub Main()
        Dim atomicExchange As New AtomicExchange()
        Dim firstThread As New Thread(AddressOf atomicExchange.Switch)
        firstThread.Start()
    End Sub

End Class

Public Class AtomicExchange

    Public Class SomeType
    End Class

    ' To use Interlocked.Exchange, someType1 
    ' must be declared as type Object.
    Dim someType1 As Object   
    Dim someType2 As SomeType 

    Sub New() 
        someType1 = New SomeType()
        someType2 = New SomeType()
    End Sub

    Sub Switch()
        someType2 = CType(Interlocked.Exchange( _
            someType1, CType(someType2, Object)), SomeType)
    End Sub

End Class

Remarks

Beginning with .NET Framework version 2.0, the Exchange<T>(T, T) method overload provides a type-safe alternative for reference types.

Exchange(IntPtr, IntPtr)

Sets a platform-specific handle or pointer to a specified value and returns the original value, as an atomic operation.

public static IntPtr Exchange (ref IntPtr location1, IntPtr value);
Parameters
location1
IntPtr

The variable to set to the specified value.

value
IntPtr

The value to which the location1 parameter is set.

Returns

The original value of location1.

Exceptions

The address of location1 is a null pointer.

Exchange(Double, Double)

Sets a double-precision floating point number to a specified value and returns the original value, as an atomic operation.

public static double Exchange (ref double location1, double value);
Parameters
location1
Double

The variable to set to the specified value.

value
Double

The value to which the location1 parameter is set.

Returns

The original value of location1.

Exceptions

The address of location1 is a null pointer.

Exchange(Int32, Int32)

Sets a 32-bit signed integer to a specified value and returns the original value, as an atomic operation.

public static int Exchange (ref int location1, int value);
Parameters
location1
Int32

The variable to set to the specified value.

value
Int32

The value to which the location1 parameter is set.

Returns

The original value of location1.

Exceptions

The address of location1 is a null pointer.

Examples

The following code example shows a thread-safe resource locking mechanism.

using namespace System;
using namespace System::Threading;

const int numThreads = 10;
const int numThreadIterations = 5;
ref class MyInterlockedExchangeExampleClass
{
public:
   static void MyThreadProc()
   {
      for ( int i = 0; i < numThreadIterations; i++ )
      {
         UseResource();
         
         //Wait 1 second before next attempt.
         Thread::Sleep( 1000 );

      }
   }


private:
   //A simple method that denies reentrancy.
   static bool UseResource()
   {
      
      //0 indicates that the method is not in use.
      if ( 0 == Interlocked::Exchange( usingResource, 1 ) )
      {
         Console::WriteLine( " {0} acquired the lock", Thread::CurrentThread->Name );
         
         //Code to access a resource that is not thread safe would go here.
         //Simulate some work
         Thread::Sleep( 500 );
         Console::WriteLine( " {0} exiting lock", Thread::CurrentThread->Name );
         
         //Release the lock
         Interlocked::Exchange( usingResource, 0 );
         return true;
      }
      else
      {
         Console::WriteLine( " {0} was denied the lock", Thread::CurrentThread->Name );
         return false;
      }
   }


   //0 for false, 1 for true.
   static int usingResource;
};

int main()
{
   Thread^ myThread;
   Random^ rnd = gcnew Random;
   for ( int i = 0; i < numThreads; i++ )
   {
      myThread = gcnew Thread( gcnew ThreadStart( MyInterlockedExchangeExampleClass::MyThreadProc ) );
      myThread->Name = String::Format( "Thread {0}", i + 1 );
      
      //Wait a random amount of time before starting next thread.
      Thread::Sleep( rnd->Next( 0, 1000 ) );
      myThread->Start();

   }
}

using System;
using System.Threading;

namespace InterlockedExchange_Example
{
    class MyInterlockedExchangeExampleClass
    {
        //0 for false, 1 for true.
        private static int usingResource = 0;

        private const int numThreadIterations = 5;
        private const int numThreads = 10;

        static void Main()
        {
            Thread myThread;
            Random rnd = new Random();

            for(int i = 0; i < numThreads; i++)
            {
                myThread = new Thread(new ThreadStart(MyThreadProc));
                myThread.Name = String.Format("Thread{0}", i + 1);
            
                //Wait a random amount of time before starting next thread.
                Thread.Sleep(rnd.Next(0, 1000));
                myThread.Start();
            }
        }

        private static void MyThreadProc()
        {
            for(int i = 0; i < numThreadIterations; i++)
            {
                UseResource();
            
                //Wait 1 second before next attempt.
                Thread.Sleep(1000);
            }
        }

        //A simple method that denies reentrancy.
        static bool UseResource()
        {
            //0 indicates that the method is not in use.
            if(0 == Interlocked.Exchange(ref usingResource, 1))
            {
                Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name);
            
                //Code to access a resource that is not thread safe would go here.
            
                //Simulate some work
                Thread.Sleep(500);

                Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name);
            
                //Release the lock
                Interlocked.Exchange(ref usingResource, 0);
                return true;
            }
            else
            {
                Console.WriteLine("   {0} was denied the lock", Thread.CurrentThread.Name);
                return false;
            }
        }

    }
}  
Imports System
Imports System.Threading

Namespace InterlockedExchange_Example
    Class MyInterlockedExchangeExampleClass
        '0 for false, 1 for true.
        Private Shared usingResource As Integer = 0

        Private Const numThreadIterations As Integer = 5
        Private Const numThreads As Integer = 10

        <MTAThread> _
        Shared Sub Main()
            Dim myThread As Thread
            Dim rnd As New Random()

            Dim i As Integer
            For i = 0 To numThreads - 1
                myThread = New Thread(AddressOf MyThreadProc)
                myThread.Name = String.Format("Thread{0}", i + 1)

                'Wait a random amount of time before starting next thread.
                Thread.Sleep(rnd.Next(0, 1000))
                myThread.Start()
            Next i
        End Sub 'Main

        Private Shared Sub MyThreadProc()
            Dim i As Integer
            For i = 0 To numThreadIterations - 1
                UseResource()

                'Wait 1 second before next attempt.
                Thread.Sleep(1000)
            Next i
        End Sub 

        'A simple method that denies reentrancy.
        Shared Function UseResource() As Boolean
            '0 indicates that the method is not in use.
            If 0 = Interlocked.Exchange(usingResource, 1) Then
                Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name)

                'Code to access a resource that is not thread safe would go here.
                'Simulate some work
                Thread.Sleep(500)

                Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name)

                'Release the lock
                Interlocked.Exchange(usingResource, 0)
                Return True
            Else
                Console.WriteLine("   {0} was denied the lock", Thread.CurrentThread.Name)
                Return False
            End If
        End Function 
    End Class 
End Namespace 

Exchange(Int64, Int64)

Sets a 64-bit signed integer to a specified value and returns the original value, as an atomic operation.

public static long Exchange (ref long location1, long value);
Parameters
location1
Int64

The variable to set to the specified value.

value
Int64

The value to which the location1 parameter is set.

Returns

The original value of location1.

Exceptions

The address of location1 is a null pointer.

Exchange<T>(T, T)

Sets a variable of the specified type T to a specified value and returns the original value, as an atomic operation.

[System.Runtime.InteropServices.ComVisible(false)]
public static T Exchange<T> (ref T location1, T value) where T : class;
Type Parameters
T

The type to be used for location1 and value. This type must be a reference type.

Parameters
location1

The variable to set to the specified value. This is a reference parameter (ref in C#, ByRef in Visual Basic).

value

The value to which the location1 parameter is set.

Returns

The original value of location1.

Exceptions

The address of location1 is a null pointer.

Examples

The following example launches ten tasks, each of which generates 100 ten-character part numbers. It then the part number that is first alphabetically.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Widget
{
   public Widget(String id)
   {
      this.Id = id;
   }

   public String Id { get; set; }
   public String Description { get; set; }
}


public class Example
{
   public static void Main()
   {
      Widget firstWidget = null;
      var tasks = new List<Task>();
      for (int ctr = 0; ctr <= 10; ctr++) {
         tasks.Add(Task.Run( () => { // Give each task its own random number generator.
                                     var rnd = new Random();
                                     for (int widgetIndex = 0; widgetIndex <= 100; widgetIndex++) {
                                        //Generate ten random characters from U+0041 to U+005A.
                                        String id = String.Empty;
                                        for (int charCtr = 0; charCtr <= 9; charCtr++)
                                           id += Convert.ToChar(rnd.Next(0x0041, 0x005B));

                                        var newWidget = new Widget(id);
                                        if (firstWidget == null)
                                           firstWidget = newWidget;
                                        else if (newWidget.Id.CompareTo(firstWidget.Id) < 0)
                                           Interlocked.Exchange(ref firstWidget, newWidget);

                                     }
                                   } ));
      }
      try {
         Task.WaitAll(tasks.ToArray());
         Console.WriteLine("The widget with the lowest id: {0}", firstWidget.Id);
      }
      catch (AggregateException ae) {
         foreach (var e in ae.InnerExceptions)
            Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message);
      }
   }
}
// The example displays output like the following:
//   The widget with the lowest id: ACHZVFBYNU
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Public Class Widget
   Public Sub New(id As String)
      Me.Id = id
   End Sub
   
   Public Property Id As String = String.Empty
   Public Property Description As String = String.Empty
End Class


Module Example
   Public Sub Main()
      Dim firstWidget As Widget = Nothing
      Dim tasks As New List(Of Task)()
      For ctr As Integer = 0 To 10
         tasks.Add(Task.Run(Sub()
                               ' Give each task its own random number generator.
                               Dim rnd As New Random()
                               For widgetIndex = 0 To 100
                                  'Generate ten random characters from U+0041 to U+005A.
                                  Dim id As String = String.Empty
                                  For charCtr As Integer = 0 To 9
                                     id += ChrW(rnd.Next(&h0041, &h005B))
                                  Next
                                  Dim newWidget As New Widget(id)
                                  If firstWidget Is Nothing Then
                                     firstWidget = newWidget
                                  Else If newWidget.Id < firstWidget.Id Then
                                     Interlocked.Exchange(firstWidget, newWidget)
                                  End If
                                Next
                             End Sub))
      Next
      Try
         Task.WaitAll(tasks.ToArray())
         Console.WriteLine("The widget with the lowest id: {0}", firstWidget.Id)
      Catch ae As AggregateException
         For Each e In ae.InnerExceptions
            Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message)
         Next
      End Try
   End Sub
End Module
' The example displays output like the following:
'   The widget with the lowest id: ACHZVFBYNU

The example uses the firstWidget variable to store the ID that occurs first in the sort order. It compares each ID that it generates with the firstWidget value. If the new value precedes the current value of firstWidget in the sort order, the example calls the Exchange method to assign the new value to firstWidget.

Remarks

This method only supports reference types. There are overloads of the Exchange method for the Int32, Int64, IntPtr, Single, and Double value types, but there is no support for other value types.

Note

This method overload is preferable to the Exchange(Object, Object) method overload, because the latter requires late-bound access to the destination object .

Applies to