Using Interlocked.CompareExchange with a class
问题 System.Threading.Interlocked.CompareExchange operator provides atomic (thus thread-safe) C# implementation of the Compare-And-Swap operation. For example int i = 5; Interlocked.CompareExchange(ref i, 10, 5); After this command, the int i would have a value = 10. And also the compare and exchange happens atomically (single operation). When I tried using this with a class instance, the compare fails and the values are not exchanged. public class X { public int y; public X(int val) { y = val; }