Interlocked.CompareExchange Metoda
Definice
Důležité
Některé informace platí pro předběžně vydaný produkt, který se může zásadně změnit, než ho výrobce nebo autor vydá. Microsoft neposkytuje žádné záruky, výslovné ani předpokládané, týkající se zde uváděných informací.
Porovná dvě hodnoty rovnosti, a pokud jsou stejné, nahradí první hodnotu.
Přetížení
CompareExchange(UIntPtr, UIntPtr, UIntPtr) |
Porovná dva popisovače nebo ukazatele rovnosti specifické pro platformu, a pokud jsou stejné, nahradí první z nich. |
CompareExchange(UInt64, UInt64, UInt64) |
Porovná dvě 64bitová celá čísla bez znaménka z hlediska rovnosti, a pokud jsou rovny, nahradí první hodnotu. |
CompareExchange(UInt32, UInt32, UInt32) |
Porovná dvě 32bitová celá čísla bez znaménka z hlediska rovnosti, a pokud jsou rovny, nahradí první hodnotu. |
CompareExchange(UInt16, UInt16, UInt16) | |
CompareExchange(Single, Single, Single) |
Porovná dvě čísla s plovoucí desetinou čárkou s jednoduchou přesností z hlediska rovnosti, a pokud jsou rovna, nahradí první hodnotu. |
CompareExchange(Object, Object, Object) |
Porovná dva objekty pro rovnost odkazu, a pokud jsou rovny, nahradí první objekt. |
CompareExchange(SByte, SByte, SByte) | |
CompareExchange(Int64, Int64, Int64) |
Porovná dvě 64bitová 64bitová celá čísla se signoumim kódem a nahradí první hodnotu, pokud jsou rovny. |
CompareExchange(Int32, Int32, Int32) |
Porovná dvě 32bitová celá čísla se signýmýmmi čísly z hlediska rovnosti, a pokud jsou rovny, nahradí první hodnotu. |
CompareExchange(Int16, Int16, Int16) | |
CompareExchange(Double, Double, Double) |
Porovná dvě čísla s plovoucí desetinou čárkou s dvojitou přesností z hlediska rovnosti, a pokud jsou rovna, nahradí první hodnotu. |
CompareExchange(Byte, Byte, Byte) | |
CompareExchange(IntPtr, IntPtr, IntPtr) |
Porovná dva popisovače nebo ukazatele rovnosti specifické pro platformu, a pokud jsou stejné, nahradí první z nich. |
CompareExchange<T>(T, T, T) |
Porovná dvě instance zadaného typu |
CompareExchange(UIntPtr, UIntPtr, UIntPtr)
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
Důležité
Toto rozhraní API neodpovídá specifikaci CLS.
Porovná dva popisovače nebo ukazatele rovnosti specifické pro platformu, a pokud jsou stejné, nahradí první z nich.
public:
static UIntPtr CompareExchange(UIntPtr % location1, UIntPtr value, UIntPtr comparand);
[System.CLSCompliant(false)]
public static UIntPtr CompareExchange (ref UIntPtr location1, UIntPtr value, UIntPtr comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : unativeint * unativeint * unativeint -> unativeint
Public Shared Function CompareExchange (ByRef location1 As UIntPtr, value As UIntPtr, comparand As UIntPtr) As UIntPtr
Parametry
- location1
-
UIntPtr
unativeint
Cíl UIntPtr, jehož hodnota je porovnána s hodnotou comparand
a případně nahrazena value
hodnotou .
- value
-
UIntPtr
unativeint
Hodnota UIntPtr , která nahradí cílovou hodnotu, pokud výsledkem porovnání bude rovnost.
Návraty
unativeint
Původní hodnota v location1
.
- Atributy
Výjimky
Adresa je location1
null
ukazatel.
Platí pro
CompareExchange(UInt64, UInt64, UInt64)
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
Důležité
Toto rozhraní API neodpovídá specifikaci CLS.
Porovná dvě 64bitová celá čísla bez znaménka z hlediska rovnosti, a pokud jsou rovny, nahradí první hodnotu.
public:
static System::UInt64 CompareExchange(System::UInt64 % location1, System::UInt64 value, System::UInt64 comparand);
[System.CLSCompliant(false)]
public static ulong CompareExchange (ref ulong location1, ulong value, ulong comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : uint64 * uint64 * uint64 -> uint64
Public Shared Function CompareExchange (ByRef location1 As ULong, value As ULong, comparand As ULong) As ULong
Parametry
- location1
- UInt64
Cíl, jehož hodnota je porovnána a comparand
případně nahrazena.
- value
- UInt64
Hodnota, která nahradí cílovou hodnotu, pokud výsledkem porovnání bude rovnost.
- comparand
- UInt64
Hodnota, která je porovnána s hodnotou v location1
.
Návraty
Původní hodnota v location1
.
- Atributy
Výjimky
Adresa je location1
null
ukazatel.
Platí pro
CompareExchange(UInt32, UInt32, UInt32)
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
Důležité
Toto rozhraní API neodpovídá specifikaci CLS.
Porovná dvě 32bitová celá čísla bez znaménka z hlediska rovnosti, a pokud jsou rovny, nahradí první hodnotu.
public:
static System::UInt32 CompareExchange(System::UInt32 % location1, System::UInt32 value, System::UInt32 comparand);
[System.CLSCompliant(false)]
public static uint CompareExchange (ref uint location1, uint value, uint comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : uint32 * uint32 * uint32 -> uint32
Public Shared Function CompareExchange (ByRef location1 As UInteger, value As UInteger, comparand As UInteger) As UInteger
Parametry
- location1
- UInt32
Cíl, jehož hodnota je porovnána a comparand
případně nahrazena.
- value
- UInt32
Hodnota, která nahradí cílovou hodnotu, pokud výsledkem porovnání bude rovnost.
- comparand
- UInt32
Hodnota, která je porovnána s hodnotou v location1
.
Návraty
Původní hodnota v location1
.
- Atributy
Výjimky
Adresa je location1
null
ukazatel.
Platí pro
CompareExchange(UInt16, UInt16, UInt16)
Důležité
Toto rozhraní API neodpovídá specifikaci CLS.
public:
static System::UInt16 CompareExchange(System::UInt16 % location1, System::UInt16 value, System::UInt16 comparand);
[System.CLSCompliant(false)]
public static ushort CompareExchange (ref ushort location1, ushort value, ushort comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : uint16 * uint16 * uint16 -> uint16
Public Shared Function CompareExchange (ByRef location1 As UShort, value As UShort, comparand As UShort) As UShort
Parametry
- location1
- UInt16
- value
- UInt16
- comparand
- UInt16
Návraty
- Atributy
Platí pro
CompareExchange(Single, Single, Single)
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
Porovná dvě čísla s plovoucí desetinou čárkou s jednoduchou přesností z hlediska rovnosti, a pokud jsou rovna, nahradí první hodnotu.
public:
static float CompareExchange(float % location1, float value, float comparand);
public static float CompareExchange (ref float location1, float value, float comparand);
static member CompareExchange : single * single * single -> single
Public Shared Function CompareExchange (ByRef location1 As Single, value As Single, comparand As Single) As Single
Parametry
- location1
- Single
Cíl, jehož hodnota je porovnána a comparand
případně nahrazena.
- value
- Single
Hodnota, která nahradí cílovou hodnotu, pokud výsledkem porovnání bude rovnost.
- comparand
- Single
Hodnota, která je porovnána s hodnotou v location1
.
Návraty
Původní hodnota v location1
.
Výjimky
Adresa je location1
nulový ukazatel.
Příklady
Následující příklad kódu ukazuje metodu bezpečnou pro přístup z více vláken, která shromažďuje průběžný součet Single hodnot. Dvě vlákna přidávají řadu Single hodnot pomocí metody bezpečné pro přístup z více vláken a běžného sčítání a po dokončení vláken jsou porovnány součty. Na počítači se dvěma procesory je v součtech významný rozdíl.
V metodě bezpečné pro přístup z více vláken se uloží počáteční hodnota mezisoučet a pak CompareExchange se metoda použije k výměně nově vypočítaného součtu za starý součet. Pokud se vrácená hodnota nerovná uložené hodnotě mezisoučet, mezitím součet aktualizovalo jiné vlákno. V takovém případě se musí pokus o aktualizaci mezisoučet opakovat.
// This example demonstrates a thread-safe method that adds to a
// running total.
using System;
using System.Threading;
public class ThreadSafe
{
// Field totalValue contains a running total that can be updated
// by multiple threads. It must be protected from unsynchronized
// access.
private float totalValue = 0.0F;
// The Total property returns the running total.
public float Total { get { return totalValue; }}
// AddToTotal safely adds a value to the running total.
public float AddToTotal(float addend)
{
float initialValue, computedValue;
do
{
// Save the current running total in a local variable.
initialValue = totalValue;
// Add the new value to the running total.
computedValue = initialValue + addend;
// CompareExchange compares totalValue to initialValue. If
// they are not equal, then another thread has updated the
// running total since this loop started. CompareExchange
// does not update totalValue. CompareExchange returns the
// contents of totalValue, which do not equal initialValue,
// so the loop executes again.
}
while (initialValue != Interlocked.CompareExchange(ref totalValue,
computedValue, initialValue));
// If no other thread updated the running total, then
// totalValue and initialValue are equal when CompareExchange
// compares them, and computedValue is stored in totalValue.
// CompareExchange returns the value that was in totalValue
// before the update, which is equal to initialValue, so the
// loop ends.
// The function returns computedValue, not totalValue, because
// totalValue could be changed by another thread between
// the time the loop ends and the function returns.
return computedValue;
}
}
public class Test
{
// Create an instance of the ThreadSafe class to test.
private static ThreadSafe ts = new ThreadSafe();
private static float control;
private static Random r = new Random();
private static ManualResetEvent mre = new ManualResetEvent(false);
public static void Main()
{
// Create two threads, name them, and start them. The
// thread will block on mre.
Thread t1 = new Thread(TestThread);
t1.Name = "Thread 1";
t1.Start();
Thread t2 = new Thread(TestThread);
t2.Name = "Thread 2";
t2.Start();
// Now let the threads begin adding random numbers to
// the total.
mre.Set();
// Wait until all the threads are done.
t1.Join();
t2.Join();
Console.WriteLine("Thread safe: {0} Ordinary float: {1}",
ts.Total, control);
}
private static void TestThread()
{
// Wait until the signal.
mre.WaitOne();
for(int i = 1; i <= 1000000; i++)
{
// Add to the running total in the ThreadSafe instance, and
// to an ordinary float.
//
float testValue = (float) r.NextDouble();
control += testValue;
ts.AddToTotal(testValue);
}
}
}
/* On a dual-processor computer, this code example produces output
similar to the following:
Thread safe: 17039.57 Ordinary float: 15706.44
*/
' This example demonstrates a thread-safe method that adds to a
' running total.
Imports System.Threading
Public Class ThreadSafe
' Field totalValue contains a running total that can be updated
' by multiple threads. It must be protected from unsynchronized
' access.
Private totalValue As Single = 0.0
' The Total property returns the running total.
Public ReadOnly Property Total As Single
Get
Return totalValue
End Get
End Property
' AddToTotal safely adds a value to the running total.
Public Function AddToTotal(ByVal addend As Single) As Single
Dim initialValue, computedValue As Single
Do
' Save the current running total in a local variable.
initialValue = totalValue
' Add the new value to the running total.
computedValue = initialValue + addend
' CompareExchange compares totalValue to initialValue. If
' they are not equal, then another thread has updated the
' running total since this loop started. CompareExchange
' does not update totalValue. CompareExchange returns the
' contents of totalValue, which do not equal initialValue,
' so the loop executes again.
Loop While initialValue <> Interlocked.CompareExchange( _
totalValue, computedValue, initialValue)
' If no other thread updated the running total, then
' totalValue and initialValue are equal when CompareExchange
' compares them, and computedValue is stored in totalValue.
' CompareExchange returns the value that was in totalValue
' before the update, which is equal to initialValue, so the
' loop ends.
' The function returns computedValue, not totalValue, because
' totalValue could be changed by another thread between
' the time the loop ends and the function returns.
Return computedValue
End Function
End Class
Public Class Test
' Create an instance of the ThreadSafe class to test.
Private Shared ts As New ThreadSafe()
Private Shared control As Single
Private Shared r As New Random()
Private Shared mre As New ManualResetEvent(false)
<MTAThread> _
Public Shared Sub Main()
' Create two threads, name them, and start them. The
' threads will block on mre.
Dim t1 As New Thread(AddressOf TestThread)
t1.Name = "Thread 1"
t1.Start()
Dim t2 As New Thread(AddressOf TestThread)
t2.Name = "Thread 2"
t2.Start()
' Now let the threads begin adding random numbers to
' the total.
mre.Set()
' Wait until all the threads are done.
t1.Join()
t2.Join()
Console.WriteLine("Thread safe: {0} Ordinary Single: {1}", ts.Total, control)
End Sub
Private Shared Sub TestThread()
' Wait until the signal.
mre.WaitOne()
For i As Integer = 1 to 1000000
' Add to the running total in the ThreadSafe instance, and
' to an ordinary Single.
'
Dim testValue As Single = r.NextDouble()
control += testValue
ts.AddToTotal(testValue)
Next
End Sub
End Class
' On a dual-processor computer, this code example produces output
' similar to the following:
'
'Thread safe: 17039.57 Ordinary Single: 15706.44
Poznámky
Pokud comparand
jsou hodnoty a v location1
shodné, uloží se value
v location1
souboru . V opačném případě se neprovádí žádná operace. Operace porovnání a výměny se provádějí jako atomická operace. Vrácená hodnota CompareExchange je původní hodnota v location1
, bez ohledu na to, jestli probíhá výměna.
Viz také
Platí pro
CompareExchange(Object, Object, Object)
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.CoreCLR.cs
Porovná dva objekty pro rovnost odkazu, a pokud jsou rovny, nahradí první objekt.
public:
static System::Object ^ CompareExchange(System::Object ^ % location1, System::Object ^ value, System::Object ^ comparand);
public static object CompareExchange (ref object location1, object value, object comparand);
public static object? CompareExchange (ref object? location1, object? value, object? comparand);
static member CompareExchange : obj * obj * obj -> obj
Public Shared Function CompareExchange (ByRef location1 As Object, value As Object, comparand As Object) As Object
Parametry
- location1
- Object
Cílový objekt, který je porovnáván odkazem s objektem comparand
a případně nahrazen.
- value
- Object
Objekt, který nahrazuje cílový objekt, pokud výsledkem porovnání odkazu je rovnost.
- comparand
- Object
Objekt porovnávaný odkazem na objekt v objektu location1
.
Návraty
Původní hodnota v location1
.
Výjimky
Adresa je location1
null
ukazatel.
Poznámky
Důležité
Počínaje rozhraním .NET Framework 2.0 CompareExchange<T>(T, T, T) poskytuje přetížení metody typově bezpečnou alternativu pro odkazové typy. Místo tohoto přetížení doporučujeme ji volat.
Pokud comparand
jsou a objekt v location1
objektu rovny odkazem, value
je uložen v location1
. V opačném případě se neprovádí žádná operace. Operace porovnání a výměny se provádějí jako atomická operace. Vrácená hodnota CompareExchange je původní hodnota v location1
, bez ohledu na to, jestli probíhá výměna.
Poznámka
Objekty se porovnávají z hlediska rovnosti odkazů, nikoli rovnosti hodnoty. V důsledku toho se dvě instance stejného typu hodnoty (například celé číslo 3) vždy zdají být nerovné a neprovádí se žádná operace. Nepoužívejte toto přetížení s typy hodnot.
Viz také
Platí pro
CompareExchange(SByte, SByte, SByte)
Důležité
Toto rozhraní API neodpovídá specifikaci CLS.
public:
static System::SByte CompareExchange(System::SByte % location1, System::SByte value, System::SByte comparand);
[System.CLSCompliant(false)]
public static sbyte CompareExchange (ref sbyte location1, sbyte value, sbyte comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : sbyte * sbyte * sbyte -> sbyte
Public Shared Function CompareExchange (ByRef location1 As SByte, value As SByte, comparand As SByte) As SByte
Parametry
- location1
- SByte
- value
- SByte
- comparand
- SByte
Návraty
- Atributy
Platí pro
CompareExchange(Int64, Int64, Int64)
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.CoreCLR.cs
Porovná dvě 64bitová 64bitová celá čísla se signoumim kódem a nahradí první hodnotu, pokud jsou rovny.
public:
static long CompareExchange(long % location1, long value, long comparand);
public static long CompareExchange (ref long location1, long value, long comparand);
static member CompareExchange : int64 * int64 * int64 -> int64
Public Shared Function CompareExchange (ByRef location1 As Long, value As Long, comparand As Long) As Long
Parametry
- location1
- Int64
Cíl, jehož hodnota je porovnána a comparand
případně nahrazena.
- value
- Int64
Hodnota, která nahradí cílovou hodnotu, pokud výsledkem porovnání bude rovnost.
- comparand
- Int64
Hodnota, která je porovnána s hodnotou v location1
.
Návraty
Původní hodnota v location1
.
Výjimky
Adresa je location1
nulový ukazatel.
Poznámky
Pokud comparand
jsou hodnoty a v location1
shodné, uloží se value
v location1
souboru . V opačném případě se neprovádí žádná operace. Operace porovnání a výměny se provádějí jako atomická operace. Vrácená hodnota CompareExchange je původní hodnota v location1
, bez ohledu na to, jestli probíhá výměna.
Viz také
Platí pro
CompareExchange(Int32, Int32, Int32)
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.CoreCLR.cs
Porovná dvě 32bitová celá čísla se signoumimi sadou pro rovnost, a pokud jsou rovna, nahradí první hodnotu.
public:
static int CompareExchange(int % location1, int value, int comparand);
public static int CompareExchange (ref int location1, int value, int comparand);
static member CompareExchange : int * int * int -> int
Public Shared Function CompareExchange (ByRef location1 As Integer, value As Integer, comparand As Integer) As Integer
Parametry
- location1
- Int32
Cíl, jehož hodnota je porovnána s comparand
a případně nahrazena.
- value
- Int32
Hodnota, která nahradí cílovou hodnotu, pokud výsledkem porovnání je rovnost.
- comparand
- Int32
Hodnota, která je porovnána s hodnotou v .location1
Návraty
Původní hodnota v location1
souboru .
Výjimky
Adresa parametru location1
je ukazatel null.
Příklady
Následující příklad kódu ukazuje metodu bezpečnou pro přístup z více vláken, která shromažďuje mezisoučet. Počáteční hodnota mezisoučet se uloží a pak CompareExchange se metoda použije k výměně nově vypočítaného součtu za starý součet. Pokud se vrácená hodnota nerovná uložené hodnotě mezisoučet, mezitím součet aktualizovalo jiné vlákno. V takovém případě se musí pokus o aktualizaci mezisoučet opakovat.
Poznámka
Metoda, zavedená Add ve verzi 2.0 rozhraní .NET Framework, poskytuje praktičtější způsob, jak nahromadit celkové součty celých čísel, které jsou bezpečné pro přístup z více vláken.
// This example demonstrates a thread-safe method that adds to a
// running total. It cannot be run directly. You can compile it
// as a library, or add the class to a project.
#using <system.dll>
using namespace System::Threading;
public ref class ThreadSafe
{
private:
// totalValue contains a running total that can be updated
// by multiple threads. It must be protected from unsynchronized
// access.
int totalValue;
public:
property int Total
{
// The Total property returns the running total.
int get()
{
return totalValue;
}
}
// AddToTotal safely adds a value to the running total.
int AddToTotal( int addend )
{
int initialValue;
int computedValue;
do
{
// Save the current running total in a local variable.
initialValue = totalValue;
// Add the new value to the running total.
computedValue = initialValue + addend;
// CompareExchange compares totalValue to initialValue. If
// they are not equal, then another thread has updated the
// running total since this loop started. CompareExchange
// does not update totalValue. CompareExchange returns the
// contents of totalValue, which do not equal initialValue,
// so the loop executes again.
}
while ( initialValue != Interlocked::CompareExchange( totalValue, computedValue, initialValue ) );
// If no other thread updated the running total, then
// totalValue and initialValue are equal when CompareExchange
// compares them, and computedValue is stored in totalValue.
// CompareExchange returns the value that was in totalValue
// before the update, which is equal to initialValue, so the
// loop ends.
// The function returns computedValue, not totalValue, because
// totalValue could be changed by another thread between
// the time the loop ends and the function returns.
return computedValue;
}
};
// This example demonstrates a thread-safe method that adds to a
// running total. It cannot be run directly. You can compile it
// as a library, or add the class to a project.
using System.Threading;
public class ThreadSafe {
// totalValue contains a running total that can be updated
// by multiple threads. It must be protected from unsynchronized
// access.
private int totalValue = 0;
// The Total property returns the running total.
public int Total {
get { return totalValue; }
}
// AddToTotal safely adds a value to the running total.
public int AddToTotal(int addend) {
int initialValue, computedValue;
do {
// Save the current running total in a local variable.
initialValue = totalValue;
// Add the new value to the running total.
computedValue = initialValue + addend;
// CompareExchange compares totalValue to initialValue. If
// they are not equal, then another thread has updated the
// running total since this loop started. CompareExchange
// does not update totalValue. CompareExchange returns the
// contents of totalValue, which do not equal initialValue,
// so the loop executes again.
} while (initialValue != Interlocked.CompareExchange(
ref totalValue, computedValue, initialValue));
// If no other thread updated the running total, then
// totalValue and initialValue are equal when CompareExchange
// compares them, and computedValue is stored in totalValue.
// CompareExchange returns the value that was in totalValue
// before the update, which is equal to initialValue, so the
// loop ends.
// The function returns computedValue, not totalValue, because
// totalValue could be changed by another thread between
// the time the loop ends and the function returns.
return computedValue;
}
}
' This example demonstrates a thread-safe method that adds to a
' running total. It cannot be run directly. You can compile it
' as a library, or add the class to a project.
Imports System.Threading
Public Class ThreadSafe
' Field totalValue contains a running total that can be updated
' by multiple threads. It must be protected from unsynchronized
' access.
Private totalValue As Integer = 0
' The Total property returns the running total.
Public ReadOnly Property Total As Integer
Get
Return totalValue
End Get
End Property
' AddToTotal safely adds a value to the running total.
Public Function AddToTotal(ByVal addend As Integer) As Integer
Dim initialValue, computedValue As Integer
Do
' Save the current running total in a local variable.
initialValue = totalValue
' Add the new value to the running total.
computedValue = initialValue + addend
' CompareExchange compares totalValue to initialValue. If
' they are not equal, then another thread has updated the
' running total since this loop started. CompareExchange
' does not update totalValue. CompareExchange returns the
' contents of totalValue, which do not equal initialValue,
' so the loop executes again.
Loop While initialValue <> Interlocked.CompareExchange( _
totalValue, computedValue, initialValue)
' If no other thread updated the running total, then
' totalValue and initialValue are equal when CompareExchange
' compares them, and computedValue is stored in totalValue.
' CompareExchange returns the value that was in totalValue
' before the update, which is equal to initialValue, so the
' loop ends.
' The function returns computedValue, not totalValue, because
' totalValue could be changed by another thread between
' the time the loop ends and the function returns.
Return computedValue
End Function
End Class
Poznámky
Pokud comparand
jsou hodnoty a v location1
rovny, value
je uložena v location1
. V opačném případě se neprovádí žádná operace. Operace porovnání a výměny se provádějí jako atomická operace. Návratová hodnota CompareExchange je původní hodnota v location1
, bez ohledu na to, zda probíhá výměna.
Viz také
Platí pro
CompareExchange(Int16, Int16, Int16)
public:
static short CompareExchange(short % location1, short value, short comparand);
public static short CompareExchange (ref short location1, short value, short comparand);
static member CompareExchange : int16 * int16 * int16 -> int16
Public Shared Function CompareExchange (ByRef location1 As Short, value As Short, comparand As Short) As Short
Parametry
- location1
- Int16
- value
- Int16
- comparand
- Int16
Návraty
Platí pro
CompareExchange(Double, Double, Double)
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
Porovná dvě čísla s plovoucí desetinou čárkou s dvojitou přesností pro rovnost, a pokud jsou rovna, nahradí první hodnotu.
public:
static double CompareExchange(double % location1, double value, double comparand);
public static double CompareExchange (ref double location1, double value, double comparand);
static member CompareExchange : double * double * double -> double
Public Shared Function CompareExchange (ByRef location1 As Double, value As Double, comparand As Double) As Double
Parametry
- location1
- Double
Cíl, jehož hodnota je porovnána s comparand
a případně nahrazena.
- value
- Double
Hodnota, která nahradí cílovou hodnotu, pokud výsledkem porovnání je rovnost.
- comparand
- Double
Hodnota, která je porovnána s hodnotou v .location1
Návraty
Původní hodnota v location1
souboru .
Výjimky
Adresa parametru location1
je ukazatel null.
Příklady
Následující příklad kódu ukazuje metodu bezpečnou z více vláken, která shromažďuje průběžný součet Double hodnot. Dvě vlákna přidávají řadu hodnot pomocí metody bezpečné pro Double vlákna a běžného sčítání a po dokončení vláken se součty porovnávají. Na počítači s dvěma procesory je v součtech významný rozdíl.
V metodě bezpečné pro přístup z více vláken se uloží počáteční hodnota průběžného součtu CompareExchange a pak se metoda použije k výměně nově vypočítaného součtu za starý součet. Pokud se návratová hodnota nerovná uložené hodnotě průběžného součtu, pak součet mezitím aktualizovalo jiné vlákno. V takovém případě se musí pokus o aktualizaci průběžného součtu opakovat.
// This example demonstrates a thread-safe method that adds to a
// running total.
using System;
using System.Threading;
public class ThreadSafe
{
// Field totalValue contains a running total that can be updated
// by multiple threads. It must be protected from unsynchronized
// access.
private double totalValue = 0.0;
// The Total property returns the running total.
public double Total { get { return totalValue; }}
// AddToTotal safely adds a value to the running total.
public double AddToTotal(double addend)
{
double initialValue, computedValue;
do
{
// Save the current running total in a local variable.
initialValue = totalValue;
// Add the new value to the running total.
computedValue = initialValue + addend;
// CompareExchange compares totalValue to initialValue. If
// they are not equal, then another thread has updated the
// running total since this loop started. CompareExchange
// does not update totalValue. CompareExchange returns the
// contents of totalValue, which do not equal initialValue,
// so the loop executes again.
}
while (initialValue != Interlocked.CompareExchange(ref totalValue,
computedValue, initialValue));
// If no other thread updated the running total, then
// totalValue and initialValue are equal when CompareExchange
// compares them, and computedValue is stored in totalValue.
// CompareExchange returns the value that was in totalValue
// before the update, which is equal to initialValue, so the
// loop ends.
// The function returns computedValue, not totalValue, because
// totalValue could be changed by another thread between
// the time the loop ends and the function returns.
return computedValue;
}
}
public class Test
{
// Create an instance of the ThreadSafe class to test.
private static ThreadSafe ts = new ThreadSafe();
private static double control;
private static Random r = new Random();
private static ManualResetEvent mre = new ManualResetEvent(false);
public static void Main()
{
// Create two threads, name them, and start them. The
// thread will block on mre.
Thread t1 = new Thread(TestThread);
t1.Name = "Thread 1";
t1.Start();
Thread t2 = new Thread(TestThread);
t2.Name = "Thread 2";
t2.Start();
// Now let the threads begin adding random numbers to
// the total.
mre.Set();
// Wait until all the threads are done.
t1.Join();
t2.Join();
Console.WriteLine("Thread safe: {0} Ordinary Double: {1}",
ts.Total, control);
}
private static void TestThread()
{
// Wait until the signal.
mre.WaitOne();
for(int i = 1; i <= 1000000; i++)
{
// Add to the running total in the ThreadSafe instance, and
// to an ordinary double.
//
double testValue = r.NextDouble();
control += testValue;
ts.AddToTotal(testValue);
}
}
}
/* On a dual-processor computer, this code example produces output
similar to the following:
Thread safe: 998068.049623744 Ordinary Double: 759775.417190589
*/
' This example demonstrates a thread-safe method that adds to a
' running total.
Imports System.Threading
Public Class ThreadSafe
' Field totalValue contains a running total that can be updated
' by multiple threads. It must be protected from unsynchronized
' access.
Private totalValue As Double = 0.0
' The Total property returns the running total.
Public ReadOnly Property Total As Double
Get
Return totalValue
End Get
End Property
' AddToTotal safely adds a value to the running total.
Public Function AddToTotal(ByVal addend As Double) As Double
Dim initialValue, computedValue As Double
Do
' Save the current running total in a local variable.
initialValue = totalValue
' Add the new value to the running total.
computedValue = initialValue + addend
' CompareExchange compares totalValue to initialValue. If
' they are not equal, then another thread has updated the
' running total since this loop started. CompareExchange
' does not update totalValue. CompareExchange returns the
' contents of totalValue, which do not equal initialValue,
' so the loop executes again.
Loop While initialValue <> Interlocked.CompareExchange( _
totalValue, computedValue, initialValue)
' If no other thread updated the running total, then
' totalValue and initialValue are equal when CompareExchange
' compares them, and computedValue is stored in totalValue.
' CompareExchange returns the value that was in totalValue
' before the update, which is equal to initialValue, so the
' loop ends.
' The function returns computedValue, not totalValue, because
' totalValue could be changed by another thread between
' the time the loop ends and the function returns.
Return computedValue
End Function
End Class
Public Class Test
' Create an instance of the ThreadSafe class to test.
Private Shared ts As New ThreadSafe()
Private Shared control As Double
Private Shared r As New Random()
Private Shared mre As New ManualResetEvent(false)
<MTAThread> _
Public Shared Sub Main()
' Create two threads, name them, and start them. The
' threads will block on mre.
Dim t1 As New Thread(AddressOf TestThread)
t1.Name = "Thread 1"
t1.Start()
Dim t2 As New Thread(AddressOf TestThread)
t2.Name = "Thread 2"
t2.Start()
' Now let the threads begin adding random numbers to
' the total.
mre.Set()
' Wait until all the threads are done.
t1.Join()
t2.Join()
Console.WriteLine("Thread safe: {0} Ordinary Double: {1}", ts.Total, control)
End Sub
Private Shared Sub TestThread()
' Wait until the signal.
mre.WaitOne()
For i As Integer = 1 to 1000000
' Add to the running total in the ThreadSafe instance, and
' to an ordinary double.
'
Dim testValue As Double = r.NextDouble
control += testValue
ts.AddToTotal(testValue)
Next
End Sub
End Class
' On a dual-processor computer, this code example produces output
' similar to the following:
'
'Thread safe: 998068.049623744 Ordinary Double: 759775.417190589
Poznámky
Pokud comparand
jsou hodnoty a v location1
rovny, value
je uložena v location1
. V opačném případě se neprovádí žádná operace. Operace porovnání a výměny se provádějí jako atomická operace. Návratová hodnota CompareExchange je původní hodnota v location1
, bez ohledu na to, zda probíhá výměna.
Viz také
Platí pro
CompareExchange(Byte, Byte, Byte)
public:
static System::Byte CompareExchange(System::Byte % location1, System::Byte value, System::Byte comparand);
public static byte CompareExchange (ref byte location1, byte value, byte comparand);
static member CompareExchange : byte * byte * byte -> byte
Public Shared Function CompareExchange (ByRef location1 As Byte, value As Byte, comparand As Byte) As Byte
Parametry
- location1
- Byte
- value
- Byte
- comparand
- Byte
Návraty
Platí pro
CompareExchange(IntPtr, IntPtr, IntPtr)
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
- Zdroj:
- Interlocked.cs
Porovná dva popisovače nebo ukazatele rovnosti specifické pro platformu, a pokud jsou si rovny, nahradí první z nich.
public:
static IntPtr CompareExchange(IntPtr % location1, IntPtr value, IntPtr comparand);
public static IntPtr CompareExchange (ref IntPtr location1, IntPtr value, IntPtr comparand);
static member CompareExchange : nativeint * nativeint * nativeint -> nativeint
Public Shared Function CompareExchange (ByRef location1 As IntPtr, value As IntPtr, comparand As IntPtr) As IntPtr
Parametry
- location1
-
IntPtr
nativeint
Cíl IntPtr, jehož hodnota je porovnána s hodnotou comparand
a případně nahrazena value
hodnotou .
- value
-
IntPtr
nativeint
Hodnota IntPtr , která nahradí cílovou hodnotu, pokud výsledkem porovnání bude rovnost.
Návraty
nativeint
Původní hodnota v location1
souboru .
Výjimky
Adresa parametru location1
je ukazatel null.
Poznámky
Pokud comparand
jsou hodnoty a v location1
rovny, value
je uložena v location1
. V opačném případě se neprovádí žádná operace. Operace porovnání a výměny se provádějí jako atomická operace. Návratová hodnota této metody je původní hodnota v location1
, bez ohledu na to, zda probíhá výměna.
Poznámka
IntPtr je typ specifický pro platformu.
Viz také
Platí pro
CompareExchange<T>(T, T, T)
- Zdroj:
- Interlocked.CoreCLR.cs
- Zdroj:
- Interlocked.CoreCLR.cs
- Zdroj:
- Interlocked.CoreCLR.cs
Porovná dvě instance zadaného typu T
odkazu pro rovnost odkazu, a pokud jsou si rovny, nahradí první z nich.
public:
generic <typename T>
where T : class static T CompareExchange(T % location1, T value, T comparand);
public static T CompareExchange<T> (ref T location1, T value, T comparand) where T : class;
[System.Runtime.InteropServices.ComVisible(false)]
public static T CompareExchange<T> (ref T location1, T value, T comparand) where T : class;
static member CompareExchange : 'T * 'T * 'T -> 'T (requires 'T : null)
[<System.Runtime.InteropServices.ComVisible(false)>]
static member CompareExchange : 'T * 'T * 'T -> 'T (requires 'T : null)
Public Shared Function CompareExchange(Of T As Class) (ByRef location1 As T, value As T, comparand As T) As T
Parametry typu
- T
Typ, který se má použít pro location1
, value
a comparand
. Tento typ musí být odkazovým typem.
Parametry
- location1
- T
Cíl, jehož hodnota je porovnána odkazem comparand
s a případně nahrazena. Toto je referenční parametr (ref
v jazyce C#, ByRef
v jazyce Visual Basic).
- value
- T
Hodnota, která nahradí cílovou hodnotu, pokud porovnání pomocí odkazu vede k rovnosti.
- comparand
- T
Hodnota, která je porovnávána odkazem na hodnotu v .location1
Návraty
Původní hodnota v location1
souboru .
- Atributy
Výjimky
Adresa parametru location1
je ukazatel null.
Poznámky
Pokud comparand
a hodnota v location1
jsou rovny odkazem, pak value
je uložena v location1
. V opačném případě se neprovádí žádná operace. Porovnání a výměna se provádějí jako atomická operace. Návratová hodnota této metody je původní hodnota v location1
, bez ohledu na to, zda probíhá výměna.
Tato metoda podporuje pouze typy odkazů. Existují přetížení CompareExchange metody pro hodnotové typy Int32, Int64, IntPtr, Singlea Double, ale není k dispozici podpora pro jiné typy hodnot.
Poznámka
Toto přetížení metody je vhodnější než CompareExchange(Object, Object, Object) přetížení metody, protože druhé vyžaduje přístup k cílovému objektu s pozdní vazbou.
Platí pro
Váš názor
https://aka.ms/ContentUserFeedback.
Připravujeme: V průběhu roku 2024 budeme postupně vyřazovat problémy z GitHub coby mechanismus zpětné vazby pro obsah a nahrazovat ho novým systémem zpětné vazby. Další informace naleznete v tématu:Odeslat a zobrazit názory pro