Export (0) Print
Expand All

Interlocked Class

Provides atomic operations for variables that are shared by multiple threads.

System.Object
  System.Threading.Interlocked

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

'Declaration
Public NotInheritable Class Interlocked

The Interlocked type exposes the following members.

  NameDescription
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsAdd(Int32, Int32)Adds two 32-bit integers and replaces the first integer with the sum, as an atomic operation.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsAdd(Int64, Int64)Adds two 64-bit integers and replaces the first integer with the sum, as an atomic operation.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsCompareExchange(Double, Double, Double)Compares two double-precision floating point numbers for equality and, if they are equal, replaces one of the values.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsCompareExchange(Int32, Int32, Int32)Compares two 32-bit signed integers for equality and, if they are equal, replaces one of the values.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsCompareExchange(Int64, Int64, Int64)Compares two 64-bit signed integers for equality and, if they are equal, replaces one of the values.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsCompareExchange(IntPtr, IntPtr, IntPtr)Compares two platform-specific handles or pointers for equality and, if they are equal, replaces one of them.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsCompareExchange(Object, Object, Object)Compares two objects for reference equality and, if they are equal, replaces one of the objects.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsCompareExchange(Single, Single, Single)Compares two single-precision floating point numbers for equality and, if they are equal, replaces one of the values.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsCompareExchange(Of T)(T, T, T)Compares two instances of the specified reference type T for equality and, if they are equal, replaces one of them.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsDecrement(Int32)Decrements a specified variable and stores the result, as an atomic operation.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsDecrement(Int64)Decrements the specified variable and stores the result, as an atomic operation.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsExchange(Double, Double)Sets a double-precision floating point number to a specified value and returns the original value, as an atomic operation.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsExchange(Int32, Int32)Sets a 32-bit signed integer to a specified value and returns the original value, as an atomic operation.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsExchange(Int64, Int64)Sets a 64-bit signed integer to a specified value and returns the original value, as an atomic operation.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsExchange(IntPtr, IntPtr)Sets a platform-specific handle or pointer to a specified value and returns the original value, as an atomic operation.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsExchange(Object, Object)Sets an object to a specified value and returns a reference to the original object, as an atomic operation.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsExchange(Single, Single)Sets a single-precision floating point number to a specified value and returns the original value, as an atomic operation.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsExchange(Of T)(T, T)Sets a variable of the specified type T to a specified value and returns the original value, as an atomic operation.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIncrement(Int32)Increments a specified variable and stores the result, as an atomic operation.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsIncrement(Int64)Increments a specified variable and stores the result, as an atomic operation.
Public methodStatic memberSupported in .NET for Windows Store appsMemoryBarrierSynchronizes memory access as follows: The processor that executes the current thread cannot reorder instructions in such a way that memory accesses before the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsReadReturns a 64-bit value, loaded as an atomic operation.
Top

The methods of this class help protect against errors that can occur when the scheduler switches contexts while a thread is updating a variable that can be accessed by other threads, or when two threads are executing concurrently on separate processors. The members of this class do not throw exceptions.

The Increment and Decrement methods increment or decrement a variable and store the resulting value in a single operation. On most computers, incrementing a variable is not an atomic operation, requiring the following steps:

  1. Load a value from an instance variable into a register.

  2. Increment or decrement the value.

  3. Store the value in the instance variable.

If you do not use Increment and Decrement, a thread can be preempted after executing the first two steps. Another thread can then execute all three steps. When the first thread resumes execution, it overwrites the value in the instance variable, and the effect of the increment or decrement performed by the second thread is lost.

The Exchange method atomically exchanges the values of the specified variables. The CompareExchange method combines two operations: comparing two values and storing a third value in one of the variables, based on the outcome of the comparison. The compare and exchange operations are performed as an atomic operation.

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

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

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

This type is thread safe.

Show:
© 2014 Microsoft