class Program
{
static long _sum;
static void Main()
{ // _sum
// 简单的自增/自减操作:
Interlocked.Increment (ref _sum); // 1
Interlocked.Decrement (ref _sum); // 0
// 加/减一个值:
Interlocked.Add (ref _sum, 3); // 3
// 读取64位字段:
Console.WriteLine (Interlocked.Read (ref _sum)); // 3
// 读取当前值并且写64位字段
// (打印 "3",并且将 _sum 更新为 10 )
Console.WriteLine (Interlocked.Exchange (ref _sum, 10)); // 10
// 仅当字段的当前值匹配特定的值(10)时才更新它:
Console.WriteLine (Interlocked.CompareExchange (ref _sum,
123, 10); // 123
}
}
https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.interlocked.compareexchange?view=net-5.0