Interlocked.Exchange Método
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Establece una variable en un valor especificado como una operación atómica.
Sobrecargas
| Exchange(UIntPtr, UIntPtr) |
Establece un puntero o identificador específico de plataforma en un valor especificado y devuelve el valor original, como una operación atómica. |
| Exchange(UInt64, UInt64) |
Establece un entero sin signo de 64 bits en un valor especificado y devuelve el valor original, como una operación atómica. |
| Exchange(UInt32, UInt32) |
Establece un entero sin signo de 32 bits en un valor especificado y devuelve el valor original, como una operación atómica. |
| Exchange(Single, Single) |
Establece un número de punto flotante de precisión sencilla en un valor especificado y devuelve el valor original, como una operación atómica. |
| Exchange(Double, Double) |
Establece un número de punto flotante de precisión doble en un valor especificado y devuelve el valor original, como una operación atómica. |
| Exchange(IntPtr, IntPtr) |
Establece un puntero o identificador específico de plataforma en un valor especificado y devuelve el valor original, como una operación atómica. |
| Exchange(Int64, Int64) |
Establece un entero de 64 bits con signo en un valor especificado y devuelve el valor original, como operación atómica. |
| Exchange(Int32, Int32) |
Establece un entero de 32 bits con signo en un valor especificado y devuelve el valor original, como una operación atómica. |
| Exchange(Object, Object) |
Establece un objeto en un valor especificado y devuelve una referencia al objeto original, como una operación atómica. |
| Exchange<T>(T, T) |
Establece una variable del tipo |
Exchange(UIntPtr, UIntPtr)
Importante
Esta API no es conforme a CLS.
Establece un puntero o identificador específico de plataforma en un valor especificado y devuelve el valor original, como una operación atómica.
public:
static UIntPtr Exchange(UIntPtr % location1, UIntPtr value);
[System.CLSCompliant(false)]
public static UIntPtr Exchange (ref UIntPtr location1, UIntPtr value);
[<System.CLSCompliant(false)>]
static member Exchange : unativeint * unativeint -> unativeint
Public Shared Function Exchange (ByRef location1 As UIntPtr, value As UIntPtr) As UIntPtr
Parámetros
- location1
-
UIntPtr
unativeint
Variable que se va a establecer en el valor especificado.
- value
-
UIntPtr
unativeint
Valor en el que está establecido el parámetro location1.
Devoluciones
-
UIntPtr
unativeint
Valor original de location1.
- Atributos
Excepciones
La dirección de location1 es un puntero null.
Se aplica a
Exchange(UInt64, UInt64)
Importante
Esta API no es conforme a CLS.
Establece un entero sin signo de 64 bits en un valor especificado y devuelve el valor original, como una operación atómica.
public:
static System::UInt64 Exchange(System::UInt64 % location1, System::UInt64 value);
[System.CLSCompliant(false)]
public static ulong Exchange (ref ulong location1, ulong value);
[<System.CLSCompliant(false)>]
static member Exchange : uint64 * uint64 -> uint64
Public Shared Function Exchange (ByRef location1 As ULong, value As ULong) As ULong
Parámetros
- location1
- UInt64
Variable que se va a establecer en el valor especificado.
- value
- UInt64
Valor en el que está establecido el parámetro location1.
Devoluciones
Valor original de location1.
- Atributos
Excepciones
La dirección de location1 es un puntero null.
Se aplica a
Exchange(UInt32, UInt32)
Importante
Esta API no es conforme a CLS.
Establece un entero sin signo de 32 bits en un valor especificado y devuelve el valor original, como una operación atómica.
public:
static System::UInt32 Exchange(System::UInt32 % location1, System::UInt32 value);
[System.CLSCompliant(false)]
public static uint Exchange (ref uint location1, uint value);
[<System.CLSCompliant(false)>]
static member Exchange : uint32 * uint32 -> uint32
Public Shared Function Exchange (ByRef location1 As UInteger, value As UInteger) As UInteger
Parámetros
- location1
- UInt32
Variable que se va a establecer en el valor especificado.
- value
- UInt32
Valor en el que está establecido el parámetro location1.
Devoluciones
Valor original de location1.
- Atributos
Excepciones
La dirección de location1 es un puntero null.
Se aplica a
Exchange(Single, Single)
Establece un número de punto flotante de precisión sencilla en un valor especificado y devuelve el valor original, como una operación atómica.
public:
static float Exchange(float % location1, float value);
public static float Exchange (ref float location1, float value);
static member Exchange : single * single -> single
Public Shared Function Exchange (ByRef location1 As Single, value As Single) As Single
Parámetros
- location1
- Single
Variable que se va a establecer en el valor especificado.
- value
- Single
Valor en el que está establecido el parámetro location1.
Devoluciones
Valor original de location1.
Excepciones
La dirección de location1 es un puntero null.
Consulte también
Se aplica a
Exchange(Double, Double)
Establece un número de punto flotante de precisión doble en un valor especificado y devuelve el valor original, como una operación atómica.
public:
static double Exchange(double % location1, double value);
public static double Exchange (ref double location1, double value);
static member Exchange : double * double -> double
Public Shared Function Exchange (ByRef location1 As Double, value As Double) As Double
Parámetros
- location1
- Double
Variable que se va a establecer en el valor especificado.
- value
- Double
Valor en el que está establecido el parámetro location1.
Devoluciones
Valor original de location1.
Excepciones
La dirección de location1 es un puntero null.
Consulte también
Se aplica a
Exchange(IntPtr, IntPtr)
Establece un puntero o identificador específico de plataforma en un valor especificado y devuelve el valor original, como una operación atómica.
public:
static IntPtr Exchange(IntPtr % location1, IntPtr value);
public static IntPtr Exchange (ref IntPtr location1, IntPtr value);
static member Exchange : nativeint * nativeint -> nativeint
Public Shared Function Exchange (ByRef location1 As IntPtr, value As IntPtr) As IntPtr
Parámetros
- location1
-
IntPtr
nativeint
Variable que se va a establecer en el valor especificado.
- value
-
IntPtr
nativeint
Valor en el que está establecido el parámetro location1.
Devoluciones
-
IntPtr
nativeint
Valor original de location1.
Excepciones
La dirección de location1 es un puntero null.
Consulte también
Se aplica a
Exchange(Int64, Int64)
Establece un entero de 64 bits con signo en un valor especificado y devuelve el valor original, como operación atómica.
public:
static long Exchange(long % location1, long value);
public static long Exchange (ref long location1, long value);
static member Exchange : int64 * int64 -> int64
Public Shared Function Exchange (ByRef location1 As Long, value As Long) As Long
Parámetros
- location1
- Int64
Variable que se va a establecer en el valor especificado.
- value
- Int64
Valor en el que está establecido el parámetro location1.
Devoluciones
Valor original de location1.
Excepciones
La dirección de location1 es un puntero null.
Consulte también
Se aplica a
Exchange(Int32, Int32)
Establece un entero de 32 bits con signo en un valor especificado y devuelve el valor original, como una operación atómica.
public:
static int Exchange(int % location1, int value);
public static int Exchange (ref int location1, int value);
static member Exchange : int * int -> int
Public Shared Function Exchange (ByRef location1 As Integer, value As Integer) As Integer
Parámetros
- location1
- Int32
Variable que se va a establecer en el valor especificado.
- value
- Int32
Valor en el que está establecido el parámetro location1.
Devoluciones
Valor original de location1.
Excepciones
La dirección de location1 es un puntero null.
La dirección de location1 es un puntero null.
Ejemplos
En el ejemplo de código siguiente se muestra un mecanismo de bloqueo de recursos seguro para subprocesos.
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.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
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
Consulte también
Se aplica a
Exchange(Object, Object)
Establece un objeto en un valor especificado y devuelve una referencia al objeto original, como una operación atómica.
public:
static System::Object ^ Exchange(System::Object ^ % location1, System::Object ^ value);
public static object Exchange (ref object location1, object value);
public static object? Exchange (ref object? location1, object? value);
static member Exchange : obj * obj -> obj
Public Shared Function Exchange (ByRef location1 As Object, value As Object) As Object
Parámetros
- location1
- Object
Variable que se va a establecer en el valor especificado.
- value
- Object
Valor en el que está establecido el parámetro location1.
Devoluciones
Valor original de location1.
Excepciones
La dirección de location1 es un puntero null.
La dirección de location1 es un puntero null.
Comentarios
Importante
A partir de .NET Framework 2.0, la sobrecarga del método Exchange<T>(T, T) proporciona una alternativa de seguridad de tipos para tipos de referencia. Se recomienda llamarlo en lugar de esta sobrecarga.
Consulte también
Se aplica a
Exchange<T>(T, T)
Establece una variable del tipo T especificado en un valor determinado y devuelve el valor original, como una operación atómica.
public:
generic <typename T>
where T : class static T Exchange(T % location1, T value);
public static T Exchange<T> (ref T location1, T value) where T : class;
[System.Runtime.InteropServices.ComVisible(false)]
public static T Exchange<T> (ref T location1, T value) where T : class;
static member Exchange : 'T * 'T -> 'T (requires 'T : null)
[<System.Runtime.InteropServices.ComVisible(false)>]
static member Exchange : 'T * 'T -> 'T (requires 'T : null)
Public Shared Function Exchange(Of T As Class) (ByRef location1 As T, value As T) As T
Parámetros de tipo
- T
Tipo que se va a usar para location1 y value. Este tipo debe ser un tipo de referencia.
Parámetros
- location1
- T
Variable que se va a establecer en el valor especificado. Este es un parámetro de referencia (ref en C#, ByRef en Visual Basic).
- value
- T
Valor en el que está establecido el parámetro location1.
Devoluciones
- T
Valor original de location1.
- Atributos
Excepciones
La dirección de location1 es un puntero null.
Comentarios
Este método solo admite tipos de referencia. Hay sobrecargas del Exchange método para los Int32tipos de valor , Int64, IntPtr, Singley Double , pero no hay compatibilidad con otros tipos de valor.
Nota
Esta sobrecarga de método es preferible a la sobrecarga del Exchange(Object, Object) método, ya que esta última requiere acceso enlazado en tiempo de ejecución al objeto de destino .