Interlocked.CompareExchange Yöntem
Tanım
Önemli
Bazı bilgiler ürünün ön sürümüyle ilgilidir ve sürüm öncesinde önemli değişiklikler yapılmış olabilir. Burada verilen bilgilerle ilgili olarak Microsoft açık veya zımni hiçbir garanti vermez.
Eşitlik için iki değeri karşılaştırır ve eşitse, atomik işlem olarak ilk değerin yerini alır.
Aşırı Yüklemeler
| Name | Description |
|---|---|
| CompareExchange(UIntPtr, UIntPtr, UIntPtr) |
Eşitlik için iki yerel boyutlu işaretsiz tamsayıyı karşılaştırır ve eşitse ilkini atomik işlem olarak değiştirir. |
| CompareExchange(UInt64, UInt64, UInt64) |
eşitlik için iki 64 bit işaretsiz tamsayıyı karşılaştırır ve eşitse, atomik işlem olarak ilk değerin yerini alır. |
| CompareExchange(UInt32, UInt32, UInt32) |
eşitlik için iki 32 bit işaretsiz tamsayıyı karşılaştırır ve eşitse, atomik bir işlem olarak ilk değerin yerini alır. |
| CompareExchange(UInt16, UInt16, UInt16) |
Eşitlik için iki 16 bit işaretli tamsayıyı karşılaştırır ve eşitse, atomik işlem olarak ilk değerin yerini alır. |
| CompareExchange(Single, Single, Single) |
Eşitlik için iki tek duyarlıklı kayan nokta sayısını karşılaştırır ve eşitse ilk değeri atomik işlem olarak değiştirir. |
| CompareExchange(Object, Object, Object) |
İki nesneyi başvuru eşitliği için karşılaştırır ve eşitse, atomik işlem olarak ilk nesnenin yerini alır. |
| CompareExchange(SByte, SByte, SByte) |
Eşitlik için iki 8 bit işaretli tamsayıyı karşılaştırır ve eşitse, atomik işlem olarak ilk değerin yerini alır. |
| CompareExchange(Int64, Int64, Int64) |
Eşitlik için iki 64 bit işaretli tamsayıyı karşılaştırır ve eşitse, atomik işlem olarak ilk değerin yerini alır. |
| CompareExchange(Int32, Int32, Int32) |
Eşitlik için iki 32 bit işaretli tamsayıyı karşılaştırır ve eşitse, atomik işlem olarak ilk değerin yerini alır. |
| CompareExchange(Int16, Int16, Int16) |
eşitlik için iki 16 bit işaretsiz tamsayıyı karşılaştırır ve eşitse, atomik bir işlem olarak ilk değerin yerini alır. |
| CompareExchange(Double, Double, Double) |
Eşitlik için iki çift duyarlıklı kayan nokta sayısını karşılaştırır ve eşitse ilk değeri atomik işlem olarak değiştirir. |
| CompareExchange(Byte, Byte, Byte) |
eşitlik için iki 8 bit işaretsiz tamsayıyı karşılaştırır ve eşitse ilk değeri atomik işlem olarak değiştirir. |
| CompareExchange(IntPtr, IntPtr, IntPtr) |
Eşitlik için iki yerel boyutlu imzalı tamsayıyı karşılaştırır ve eşitse ilkini atomik işlem olarak değiştirir. |
| CompareExchange<T>(T, T, T) |
Belirtilen türün |
CompareExchange(UIntPtr, UIntPtr, UIntPtr)
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
Önemli
Bu API, CLS uyumlu değildir.
Eşitlik için iki yerel boyutlu işaretsiz tamsayıyı karşılaştırır ve eşitse ilkini atomik işlem olarak değiştirir.
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
Parametreler
- location1
-
UIntPtr
unativeint
Değeri değeri ile comparand karşılaştırılan ve muhtemelen ile değiştirilen valuehedef.
- value
-
UIntPtr
unativeint
Karşılaştırma eşitlikle sonuçlanırsa hedef değerin yerini alan değer.
- comparand
-
UIntPtr
unativeint
konumundaki değerle karşılaştırılan değer location1.
Döndürülenler
unativeint
içindeki location1özgün değer.
- Öznitelikler
Özel durumlar
adresi location1 bir null işaretçidir.
Şunlara uygulanır
CompareExchange(UInt64, UInt64, UInt64)
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
Önemli
Bu API, CLS uyumlu değildir.
eşitlik için iki 64 bit işaretsiz tamsayıyı karşılaştırır ve eşitse, atomik işlem olarak ilk değerin yerini alır.
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
Parametreler
- location1
- UInt64
Değeri ile comparand karşılaştırılan ve büyük olasılıkla değiştirilen hedef.
- value
- UInt64
Karşılaştırma eşitlikle sonuçlanırsa hedef değerin yerini alan değer.
- comparand
- UInt64
konumundaki değerle karşılaştırılan değer location1.
Döndürülenler
içindeki location1özgün değer.
- Öznitelikler
Özel durumlar
adresi location1 bir null işaretçidir.
Şunlara uygulanır
CompareExchange(UInt32, UInt32, UInt32)
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
Önemli
Bu API, CLS uyumlu değildir.
eşitlik için iki 32 bit işaretsiz tamsayıyı karşılaştırır ve eşitse, atomik bir işlem olarak ilk değerin yerini alır.
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
Parametreler
- location1
- UInt32
Değeri ile comparand karşılaştırılan ve büyük olasılıkla değiştirilen hedef.
- value
- UInt32
Karşılaştırma eşitlikle sonuçlanırsa hedef değerin yerini alan değer.
- comparand
- UInt32
konumundaki değerle karşılaştırılan değer location1.
Döndürülenler
içindeki location1özgün değer.
- Öznitelikler
Özel durumlar
adresi location1 bir null işaretçidir.
Şunlara uygulanır
CompareExchange(UInt16, UInt16, UInt16)
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
Önemli
Bu API, CLS uyumlu değildir.
Eşitlik için iki 16 bit işaretli tamsayıyı karşılaştırır ve eşitse, atomik işlem olarak ilk değerin yerini alır.
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
Parametreler
- location1
- UInt16
Değeri ile comparand karşılaştırılan ve büyük olasılıkla değiştirilen hedef.
- value
- UInt16
Karşılaştırma eşitlikle sonuçlanırsa hedef değerin yerini alan değer.
- comparand
- UInt16
konumundaki değerle karşılaştırılan değer location1.
Döndürülenler
içindeki location1özgün değer.
- Öznitelikler
Özel durumlar
adresi location1 bir null işaretçidir.
Şunlara uygulanır
CompareExchange(Single, Single, Single)
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
Eşitlik için iki tek duyarlıklı kayan nokta sayısını karşılaştırır ve eşitse ilk değeri atomik işlem olarak değiştirir.
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
Parametreler
- location1
- Single
Değeri ile comparand karşılaştırılan ve büyük olasılıkla değiştirilen hedef.
- value
- Single
Karşılaştırma eşitlikle sonuçlanırsa hedef değerin yerini alan değer.
- comparand
- Single
konumundaki değerle karşılaştırılan değer location1.
Döndürülenler
içindeki location1özgün değer.
Özel durumlar
adresi location1 null bir işaretçidir.
Örnekler
Aşağıdaki kod örneği, çalışan Single toplam değeri biriktiren iş parçacığı güvenli bir yöntemi gösterir. İki iş parçacığı, iş parçacığı güvenli yöntemini ve normal toplamayı kullanarak bir dizi Single değer ekler ve iş parçacıkları tamamlandığında toplamlar karşılaştırılır. Çift işlemcili bir bilgisayarda, toplamlarda önemli bir fark vardır.
İş parçacığı güvenli yönteminde, çalışan toplamın ilk değeri kaydedilir ve yeni CompareExchange hesaplanan toplamı eski toplamla değiştirmek için yöntemi kullanılır. Dönüş değeri, çalışan toplamın kaydedilen değerine eşit değilse, başka bir iş parçacığı bu arada toplamı güncelleştirmiştir. Bu durumda, çalışan toplamı güncelleştirme girişimi yinelenmelidir.
// 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
Açıklamalar
ve değeri location1 eşitse comparand içinde value depolanırlocation1. Aksi takdirde hiçbir işlem gerçekleştirilmez. Karşılaştırma ve değişim işlemleri atomik bir işlem olarak gerçekleştirilir. değerinin CompareExchange dönüş değeri, değişimin gerçekleşip gerçekleşmediğine bakılmaksızın içindeki location1özgün değerdir.
Ayrıca bkz.
Şunlara uygulanır
CompareExchange(Object, Object, Object)
- Kaynak:
- Interlocked.CoreCLR.cs
- Kaynak:
- Interlocked.CoreCLR.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.CoreCLR.cs
İki nesneyi başvuru eşitliği için karşılaştırır ve eşitse, atomik işlem olarak ilk nesnenin yerini alır.
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
Parametreler
- location1
- Object
Başvuruyla comparand karşılaştırılan ve büyük olasılıkla değiştirilen hedef nesne.
- value
- Object
Başvuru karşılaştırması eşitlikle sonuçlanırsa hedef nesnenin yerini alan nesne.
- comparand
- Object
konumundaki nesnesine başvuruyla karşılaştırılan nesne location1.
Döndürülenler
içindeki location1özgün değer.
Özel durumlar
adresi location1 bir null işaretçidir.
Açıklamalar
Önemli
Yöntem CompareExchange<T>(T, T, T) aşırı yüklemesi, somut başvuru türleri için kullanılabilecek genel bir alternatif sağlar.
ve içindeki location1 nesnesi başvuruya göre eşitse comparand içinde value depolanırlocation1. Aksi takdirde hiçbir işlem gerçekleştirilmez. Karşılaştırma ve değişim işlemleri atomik bir işlem olarak gerçekleştirilir. değerinin CompareExchange dönüş değeri, değişimin gerçekleşip gerçekleşmediğine bakılmaksızın içindeki location1özgün değerdir.
Not
Nesneler değer eşitliği yerine başvuru eşitliği için karşılaştırılır. Sonuç olarak, aynı değer türündeki iki kutulu örnek (örneğin, 3 tamsayısı) her zaman eşit değil gibi görünür ve hiçbir işlem yapılmaz. Bu aşırı yüklemeyi değer türleriyle kullanmayın.
Ayrıca bkz.
Şunlara uygulanır
CompareExchange(SByte, SByte, SByte)
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
Önemli
Bu API, CLS uyumlu değildir.
Eşitlik için iki 8 bit işaretli tamsayıyı karşılaştırır ve eşitse, atomik işlem olarak ilk değerin yerini alır.
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
Parametreler
- location1
- SByte
Değeri ile comparand karşılaştırılan ve büyük olasılıkla değiştirilen hedef.
- value
- SByte
Karşılaştırma eşitlikle sonuçlanırsa hedef değerin yerini alan değer.
- comparand
- SByte
konumundaki değerle karşılaştırılan değer location1.
Döndürülenler
içindeki location1özgün değer.
- Öznitelikler
Özel durumlar
adresi location1 bir null işaretçidir.
Şunlara uygulanır
CompareExchange(Int64, Int64, Int64)
- Kaynak:
- Interlocked.CoreCLR.cs
- Kaynak:
- Interlocked.CoreCLR.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.CoreCLR.cs
Eşitlik için iki 64 bit işaretli tamsayıyı karşılaştırır ve eşitse, atomik işlem olarak ilk değerin yerini alır.
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
Parametreler
- location1
- Int64
Değeri ile comparand karşılaştırılan ve büyük olasılıkla değiştirilen hedef.
- value
- Int64
Karşılaştırma eşitlikle sonuçlanırsa hedef değerin yerini alan değer.
- comparand
- Int64
konumundaki değerle karşılaştırılan değer location1.
Döndürülenler
içindeki location1özgün değer.
Özel durumlar
adresi location1 null bir işaretçidir.
Açıklamalar
ve değeri location1 eşitse comparand içinde value depolanırlocation1. Aksi takdirde hiçbir işlem gerçekleştirilmez. Karşılaştırma ve değişim işlemleri atomik bir işlem olarak gerçekleştirilir. değerinin CompareExchange dönüş değeri, değişimin gerçekleşip gerçekleşmediğine bakılmaksızın içindeki location1özgün değerdir.
Ayrıca bkz.
Şunlara uygulanır
CompareExchange(Int32, Int32, Int32)
- Kaynak:
- Interlocked.CoreCLR.cs
- Kaynak:
- Interlocked.CoreCLR.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.CoreCLR.cs
Eşitlik için iki 32 bit işaretli tamsayıyı karşılaştırır ve eşitse, atomik işlem olarak ilk değerin yerini alır.
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
Parametreler
- location1
- Int32
Değeri ile comparand karşılaştırılan ve büyük olasılıkla değiştirilen hedef.
- value
- Int32
Karşılaştırma eşitlikle sonuçlanırsa hedef değerin yerini alan değer.
- comparand
- Int32
konumundaki değerle karşılaştırılan değer location1.
Döndürülenler
içindeki location1özgün değer.
Özel durumlar
adresi location1 null bir işaretçidir.
Örnekler
Aşağıdaki kod örneği, çalışan bir toplamı biriktiren iş parçacığı güvenli bir yöntemi gösterir. Çalışan toplamın ilk değeri kaydedilir ve yeni CompareExchange hesaplanan toplamı eski toplamla değiştirmek için yöntemi kullanılır. Dönüş değeri, çalışan toplamın kaydedilen değerine eşit değilse, başka bir iş parçacığı bu arada toplamı güncelleştirmiştir. Bu durumda, çalışan toplamı güncelleştirme girişimi yinelenmelidir.
Not
yöntemi, Add tamsayılar için iş parçacığı güvenli çalışan toplamları biriktirmek için daha kullanışlı bir yol sağlar.
// 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
Açıklamalar
ve değeri location1 eşitse comparand içinde value depolanırlocation1. Aksi takdirde hiçbir işlem gerçekleştirilmez. Karşılaştırma ve değişim işlemleri atomik bir işlem olarak gerçekleştirilir. değerinin CompareExchange dönüş değeri, değişimin gerçekleşip gerçekleşmediğine bakılmaksızın içindeki location1özgün değerdir.
Ayrıca bkz.
Şunlara uygulanır
CompareExchange(Int16, Int16, Int16)
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
eşitlik için iki 16 bit işaretsiz tamsayıyı karşılaştırır ve eşitse, atomik bir işlem olarak ilk değerin yerini alır.
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
Parametreler
- location1
- Int16
Değeri ile comparand karşılaştırılan ve büyük olasılıkla değiştirilen hedef.
- value
- Int16
Karşılaştırma eşitlikle sonuçlanırsa hedef değerin yerini alan değer.
- comparand
- Int16
konumundaki değerle karşılaştırılan değer location1.
Döndürülenler
içindeki location1özgün değer.
Özel durumlar
adresi location1 bir null işaretçidir.
Şunlara uygulanır
CompareExchange(Double, Double, Double)
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
Eşitlik için iki çift duyarlıklı kayan nokta sayısını karşılaştırır ve eşitse ilk değeri atomik işlem olarak değiştirir.
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
Parametreler
- location1
- Double
Değeri ile comparand karşılaştırılan ve büyük olasılıkla değiştirilen hedef.
- value
- Double
Karşılaştırma eşitlikle sonuçlanırsa hedef değerin yerini alan değer.
- comparand
- Double
konumundaki değerle karşılaştırılan değer location1.
Döndürülenler
içindeki location1özgün değer.
Özel durumlar
adresi location1 null bir işaretçidir.
Örnekler
Aşağıdaki kod örneği, çalışan Double toplam değeri biriktiren iş parçacığı güvenli bir yöntemi gösterir. İki iş parçacığı, iş parçacığı güvenli yöntemini ve normal toplamayı kullanarak bir dizi Double değer ekler ve iş parçacıkları tamamlandığında toplamlar karşılaştırılır. Çift işlemcili bir bilgisayarda, toplamlarda önemli bir fark vardır.
İş parçacığı güvenli yönteminde, çalışan toplamın ilk değeri kaydedilir ve yeni CompareExchange hesaplanan toplamı eski toplamla değiştirmek için yöntemi kullanılır. Dönüş değeri, çalışan toplamın kaydedilen değerine eşit değilse, başka bir iş parçacığı bu arada toplamı güncelleştirmiştir. Bu durumda, çalışan toplamı güncelleştirme girişimi yinelenmelidir.
// 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
Açıklamalar
ve değeri location1 eşitse comparand içinde value depolanırlocation1. Aksi takdirde hiçbir işlem gerçekleştirilmez. Karşılaştırma ve değişim işlemleri atomik bir işlem olarak gerçekleştirilir. değerinin CompareExchange dönüş değeri, değişimin gerçekleşip gerçekleşmediğine bakılmaksızın içindeki location1özgün değerdir.
Ayrıca bkz.
Şunlara uygulanır
CompareExchange(Byte, Byte, Byte)
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
eşitlik için iki 8 bit işaretsiz tamsayıyı karşılaştırır ve eşitse ilk değeri atomik işlem olarak değiştirir.
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
Parametreler
- location1
- Byte
Değeri ile comparand karşılaştırılan ve büyük olasılıkla değiştirilen hedef.
- value
- Byte
Karşılaştırma eşitlikle sonuçlanırsa hedef değerin yerini alan değer.
- comparand
- Byte
konumundaki değerle karşılaştırılan değer location1.
Döndürülenler
içindeki location1özgün değer.
Özel durumlar
adresi location1 bir null işaretçidir.
Şunlara uygulanır
CompareExchange(IntPtr, IntPtr, IntPtr)
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
Eşitlik için iki yerel boyutlu imzalı tamsayıyı karşılaştırır ve eşitse ilkini atomik işlem olarak değiştirir.
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
Parametreler
- location1
-
IntPtr
nativeint
Değeri değeri ile comparand karşılaştırılan ve muhtemelen ile değiştirilen valuehedef.
- value
-
IntPtr
nativeint
Karşılaştırma eşitlikle sonuçlanırsa hedef değerin yerini alan değer.
- comparand
-
IntPtr
nativeint
konumundaki değerle karşılaştırılan değer location1.
Döndürülenler
nativeint
içindeki location1özgün değer.
Özel durumlar
adresi location1 null bir işaretçidir.
Açıklamalar
ve değeri location1 eşitse comparand içinde value depolanırlocation1. Aksi takdirde hiçbir işlem gerçekleştirilmez. Karşılaştırma ve değişim işlemleri atomik bir işlem olarak gerçekleştirilir. Bu yöntemin dönüş değeri, değişimin gerçekleşip gerçekleşmediğine bakılmaksızın içindeki location1özgün değerdir.
Not
IntPtr platforma özgü bir türdür.
Ayrıca bkz.
Şunlara uygulanır
CompareExchange<T>(T, T, T)
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.cs
- Kaynak:
- Interlocked.CoreCLR.cs
- Kaynak:
- Interlocked.CoreCLR.cs
- Kaynak:
- Interlocked.CoreCLR.cs
Belirtilen türün T iki örneğini başvuru eşitliği için karşılaştırır ve eşitse, atomik işlem olarak ilkinin yerini alır.
public:
generic <typename T>
where T : class static T CompareExchange(T % location1, T value, T comparand);
public:
generic <typename T>
static T CompareExchange(T % location1, T value, T comparand);
public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class;
public static T CompareExchange<T>(ref T location1, T value, T comparand);
[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)
static member CompareExchange : 'T * 'T * 'T -> 'T
[<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
Public Shared Function CompareExchange(Of T) (ByRef location1 As T, value As T, comparand As T) As T
Tür Parametreleri
- T
, valueve comparandiçin location1kullanılacak tür.
Parametreler
- location1
- T
Değeri ile başvuruyla comparand karşılaştırılan ve büyük olasılıkla değiştirilmiş olan hedef. Bu bir başvuru parametresidir (C# dilinde ref, Visual Basic'de ByRef).
- value
- T
Başvuruya göre karşılaştırma eşitlikle sonuçlanırsa hedef değerin yerini alan değer.
- comparand
- T
konumundaki değere başvuruyla karşılaştırılan değer location1.
Döndürülenler
içindeki location1özgün değer.
- Öznitelikler
Özel durumlar
adresi location1 null bir işaretçidir.
Desteklenmeyen T bir belirtildi. .NET 8 ve önceki sürümlerde, T bir başvuru türü olmalıdır. .NET 9 ve sonraki sürümlerde T bir başvuru, ilkel veya sabit listesi türünde olmalıdır.
Açıklamalar
ve içindeki location1 değeri başvuruya göre eşitse comparand içinde value depolanırlocation1. Aksi takdirde hiçbir işlem gerçekleştirilmez. Karşılaştırma ve değişim atomik bir işlem olarak gerçekleştirilir. Bu yöntemin dönüş değeri, değişimin gerçekleşip gerçekleşmediğine bakılmaksızın içindeki location1özgün değerdir.