方法签名:public static int CompareExchange(ref int location1, int value, int comparand); location1与comparand进行比较,如果相等,则用value替换location1的值,并返回location1被替换之前的值,例如:
1 2 3
int a = 0; int b = Interlocked.CompareExchange(ref a, 1, 0); Console.WriteLine($"a is {a}, b is {b}");
//模拟多线程操作 var calculationHelper = new CalculationHelper(); int ordinaryValue = 0; ManualResetEventSlim manualResetEvent = new ManualResetEventSlim(false);
Thread thread1 = new Thread(new ThreadStart(Test)); thread1.Name = "线程1"; thread1.Start();
Thread thread2 = new Thread(new ThreadStart(Test)); thread2.Name = "线程2"; thread2.Start();