Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.
1 out of 10 rated this helpful - Rate this topic

Interlocked Class

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

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

public static class Interlocked
public final class Interlocked
public final class Interlocked

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.

using System;
using System.Threading;

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

        private static Object currentMso;
        private static Object globalMso = new Object();
        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;
            }
        }

    }
}  

package InterlockedExchange_Example ; 

import System .* ;
import System.Threading .* ;
import System.Threading.Thread;

class MyInterlockedExchangeExampleClass
{
    //0 for false, 1 for true.
    private static int usingResource = 0;
    private static Object currentMso;
    private static Object globalMso = new Object();
    private static int numThreadIterations = 5;
    private static int numThreads = 10;

    public static void main(String[] args)
    {
        Thread myThread;
        Random rnd = new Random();

        for (int i = 0; i < numThreads; i++) {
            myThread = new Thread(new ThreadStart(MyThreadProc));
            myThread.set_Name(String.Format("Thread{0}",
                String.valueOf(i + 1)));

            //Wait a random amount of time before starting next thread.
            Thread.Sleep(rnd.Next(0, 1000));
            myThread.Start();
        }
    } //main

    private static void MyThreadProc()
    {
        for (int i = 0; i < numThreadIterations; i++) {
            UseResource();

            //Wait 1 second before next attempt.
            Thread.Sleep(1000);
        }
    } //MyThreadProc

    //A simple method that denies reentrancy.
    static boolean UseResource()
    {
        //0 indicates that the method is not in use.
        if (0 == Interlocked.Exchange(usingResource, 1)) {
            Console.WriteLine("{0} acquired the lock",
                Thread.get_CurrentThread().get_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.get_CurrentThread().get_Name());

            //Release the lock
            Interlocked.Exchange(usingResource, 0);
            return true;
        }
        else {
            Console.WriteLine("   {0} was denied the lock", 
                Thread.get_CurrentThread().get_Name());
            return false;
        }
    } //UseResource
} //MyInterlockedExchangeExampleClass

System.Object
  System.Threading.Interlocked

This type is thread safe.

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

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

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft. All rights reserved.