Use Of Volatile Statement In C# Language

Introduction

Volatile modifier is use to reduce concurrency issues  of executing threads. Volatile apply for reference type, pointer type , enum type with an integral base type and integral type such as sbyte, sort, usort, int, unit, char, float, and bool. Volatile modifier does not force synchronization of load and store, it means volatile does not work as a lock statement. Volatile modifier provides a way for you to restrict the optimizations the compiler makes regarding loads and stores into the field. You will typically use volatile in multithreaded programs and with flag variables. A read and write to a volatile field is always done after all other memory accesses, which precede in the instruction sequence.

Example

using System;

using System.Threading;

 

namespace volatile_statement_in_c_sharp

{

    public class A    //Create class

    {

         string show; //create state variable, which type of string

        public volatile bool flage;  //create volatile field

        public void set_volatile() //create function

        {

            show = "Dot net Heven"; //set value of string

            flage = true;

            Thread.Sleep(300);     //sleep thread 300 milliseconds

            check_volatile();      //call check volatile() function

        }

    

        public void check_volatile()

        {

            if (flage)   // check falge's value

            {

                Console.WriteLine(show);

                Console.WriteLine("Flage is:{0}", flage);

            }

        }

       

    }

    class Program

    {

        static void Main(string[] args)

        {

            A obj = new A(); //create object of class A

           

            ThreadStart th = new ThreadStart(obj.set_volatile); //create thread

            new Thread(th).Start();          //start thread

            Console.ReadLine();            

        }

    }

}

Output:


output.jpg


Ebook Download
View all
Learn
View all