Interlocked : Interlocked « Thread « C# / CSharp Tutorial






using System;
using System.Threading;

class MainClass
{
    public static void Main()
    {
        int firstInt = 1;
        int secondInt = 2;

        Console.WriteLine("firstInt initial value = {0}", firstInt);
        Console.WriteLine("secondInt initial value = {0}", secondInt);

        Interlocked.Decrement(ref firstInt);

        Console.WriteLine(Environment.NewLine); 
        Console.WriteLine("firstInt after decrement = {0}", firstInt);

        Interlocked.Increment(ref secondInt);

        Console.WriteLine("secondInt after increment = {0}", secondInt);

        Interlocked.Add(ref firstInt, secondInt);

        Console.WriteLine(Environment.NewLine); 
        Console.WriteLine("firstInt after Add = {0}", firstInt);
        Console.WriteLine("secondInt after Add = {0}", secondInt);

        Interlocked.Exchange(ref secondInt, firstInt);

        Console.WriteLine(Environment.NewLine); 
        Console.WriteLine("firstInt after Exchange = {0}", firstInt);
        Console.WriteLine("secondInt after Exchange = {0}", secondInt);

        Interlocked.CompareExchange(ref firstInt, 5000, secondInt);

        Console.WriteLine(Environment.NewLine); 
        Console.WriteLine("firstInt after CompareExchange = {0}", firstInt);
        Console.WriteLine("secondInt after CompareExchange = {0}", secondInt);

    }
}
firstInt initial value = 1
secondInt initial value = 2


firstInt after decrement = 0
secondInt after increment = 3


firstInt after Add = 3
secondInt after Add = 3


firstInt after Exchange = 3
secondInt after Exchange = 3


firstInt after CompareExchange = 5000
secondInt after CompareExchange = 3








20.14.Interlocked
20.14.1.Use the Interlocked object
20.14.2.Use Interlocked operations
20.14.3.Interlocked.Increment and Interlocked.Decrement
20.14.4.Interlocked