Interlocked : Interlocked : Thread C# Examples


C# Examples » Thread » Interlocked »

 

Interlocked









    
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);

        }
}
    
   
  
   



Output

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


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Thread
» Interlocked