Cliquez pour évaluer et commenter
MSDN
MSDN Library
Développement .NET
Versions précédentes
.NET Framework SDK 2.0
Class Library Reference
System.Threading
Interlocked, classe
Méthodes Interlocked
Exchange, méthode
 Exchange, méthode (Int32, Int32)

  Passer à l'affichage pour faible bande passante
Cette page est spécifique à
Microsoft Visual Studio 2005/.NET Framework 2.0

D'autres versions sont également disponibles pour :
Bibliothèque de classes .NET Framework
Interlocked.Exchange, méthode (Int32, Int32)

Définit une valeur spécifiée pour un entier signé de 32 bits, puis retourne la valeur d'origine, sous la forme d'une opération atomique.

Espace de noms : System.Threading
Assembly : mscorlib (dans mscorlib.dll)

Visual Basic (Déclaration)
Public Shared Function Exchange ( _
    ByRef location1 As Integer, _
    value As Integer _
) As Integer
Visual Basic (Utilisation)
Dim location1 As Integer
Dim value As Integer
Dim returnValue As Integer

returnValue = Interlocked.Exchange(location1, value)
C#
public static int Exchange (
    ref int location1,
    int value
)
C++
public:
static int Exchange (
    int% location1, 
    int value
)
J#
public static int Exchange (
    /** @ref */ int location1, 
    int value
)
JScript
JScript ne prend pas en charge le passage d'arguments de type valeur par référence.

Paramètres

location1

Variable à laquelle affecter la valeur spécifiée.

value

Valeur affectée au paramètre location1.

Valeur de retour

Valeur d'origine de location1.
Type d'exceptionCondition

ArgumentNullException

L'adresse de location1 est un pointeur null.

L'exemple de code suivant illustre un mécanisme de verrouillage de ressources thread-safe.

Visual Basic
Imports System
Imports System.Threading

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

        Private Shared currentMso As [Object]
        Private Shared globalMso As New [Object]()
        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 'MyThreadProc

        '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 'UseResource
    End Class 'MyInterlockedExchangeExampleClass 
End Namespace 'InterlockedExchange_Example
C#
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;
            }
        }

    }
}  
C++
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;
   static Object^ globalMso = gcnew Object;
};

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();

   }
}

J#
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

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Édition Media Center, Windows XP Professionnel Édition x64, Windows XP SP2, Windows XP Starter Edition

Le .NET Framework ne prend pas en charge toutes les versions de chaque plate-forme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise.

.NET Framework

Prise en charge dans : 2.0, 1.1, 1.0

.NET Compact Framework

Prise en charge dans : 2.0, 1.0
Contenu de la communauté   Qu'est-ce que le Contenu de la communauté ?
Ajouter du contenu RSS  Annotations
Processing
© 2009 Microsoft Corporation. Tous droits réservés. Conditions d'utilisation  |  Marques  |  Confidentialité
Page view tracker