volatile keyword in C#


To reduce concurrency issues in C#, use the volatile keyword. Let us seen an example.

The following is how you use a volatile keyword for public variable −

class Program {
   public volatile int a;
   public void Program(int _a) {
      i = _i;
   }
}

Let us see another example: We have two static variables. Set them in a new method −

_out = "Welcome!";
_new = true;

We declared them as static before using volatile −

static string _out;
static volatile bool new;

Now you need to run the method on a thread −

new Thread(new ThreadStart(volatileFunc)).Start();

Read the value of the volatile variable −

if (_new) {
   Console.WriteLine(_out);
}

Updated on: 20-Jun-2020

584 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements