C#

What Is The Use Of Volatile Keyword In C#

A variable’s value must never be cached in C#  because it may change outside of the scope of the program itself. Compiler optimizations that may cause problems if the variable changes “outside of its control” will be avoided.
But in case if we need a field variable to be modified within the program by means such as the operating system, concurrently executing thread or the hardware then we can use Volatile keyword for that field.

Volatile Keyword in C #

Understanding what happens when a variable is not volatile is critical to understanding what volatile does.

Non-volatile Variable

There will always be a local copy of the variable in each thread’s cache when accessing a non-volatile variable between two threads. There will be no way for the thread 1 to see any changes made in its local cache by thread 2.

Volatile Variable in C#

Volatile Modifier ensures that one thread retrieves the most up to date value written by another thread without the use of the Lock statement.

Since variables are prone to change it’s important to note that when a variable is declared volatile, it means that threads should not store the value of the variable in their own memory, or in other words, the values of these variables should not be trusted by other threads.

When to Use Volatile Variables in C#?

Any time a variable’s value is modified by another thread, process, or outside the program, you want all threads to receive the most up-to-date copy of the variable’s value.

Semantics have been added to volatile field readings. In other words, any subsequent memory reads will be preceded by the read from the volatile variable. For weakly ordered CPUs, it will use a special instruction to flush any reads that occur after the volatile read but were speculatively started early, or the CPU could prevent them from being issued early in the first place, by preventing any speculative load occurring between the issue of an acquire and its retirement.

All memory writes to the volatile variable will be delayed until all previous memory writes have been made visible to other processors.

Only class or struct level fields can use the volatile keyword.

There is no way to make a local variable as volatile.

C# Volatile Keyword  Example

Volatile keyword can be used for fields of the following types

  • Basic primitive types such as  short, ushort, int, uint, float, char, sbyte, byte and bool.
  • IntPtr and UIntPtr.
  • Enum type with base types such as short, ushort, int,uint,byte orsbyte
  • Reference type objects
  • Pointers
  • Generic reference type parameters

We can declare a variable volatile variable by using the modifier keyword volatile for the variable. See below declarations,

private volatile int intVolatile; 
static volatile bool isSuccess;

We can not mark types such as long and double as volatile since there is no guarantee that reads and writes to the fields of these types will be atomic. The Interlocked class members or the lock statement can be used to protect multi-threaded access to these kind of type fields.

Cons Of Volatile Keyword in C#

In many cases, the volatile keyword helps in thread safety, but by itself it will not solve all your concurrency problems.

You can reorder the code if you don’t use volatile variables. The compiler is free to write to the cache value of volatile variables rather than reading from the main memory. No reordering or optimization can take place when declared variables as volatile.

A variable or object marked as volatile does not mean that you don’t need to use the lock keyword in your program at all. It is not a substitute for the lock keyword. 

Using a volatile read on a multiprocessor system doesn’t guarantee that you’ll get the most recent value written to that memory location. Furthermore, a volatile write operation does not guarantee that other processors will see the value that was written.

FAQ on volatile keyword C#

What are the keywords in C#?

The compiler uses predefined, reserved identifiers known as keywords. But in case to use them as identifiers in code, we must prefix them with @.

Examples of few keywords in C# are,  namespace, class, delegate, abstract, char, const, enum etc.

What is volatile keyword used for?

Multi threaded programs benefit from this. It’s possible to change the value of a variable using the volatile keyword from different threads. Multiple threads can use a method and instance of the classes at the same time without any problem

Volatile keyword reduces concurrency issues.

Will volatile fields cause a performance problem?

There will be performance impact in certain cases. If possible, it is best to avoid using volatile keyword.

Summary

In this article we covered what is volatile keyword in C#, advantages of volatile keyword  and its uses. Hope this article helped you. Leave your feedback in the comments section below.
Rajeev

Recent Posts

OWIN Authentication in .NET Core

OWIN (Open Web Interface for .NET) is an interface between web servers and web applications…

2 years ago

Serializing and Deserializing JSON using Jsonconvertor in C#

JSON (JavaScript Object Notation) is a commonly used data exchange format that facilitates data exchange…

2 years ago

What is CAP Theorem? | What is Brewer’s Theorem?

The CAP theorem is also known as Brewer's theorem. What is CAP Theorem? CAP theorem…

2 years ago

SOLID -Basic Software Design Principles

Some of the Key factors that need to consider while architecting or designing a software…

2 years ago

What is Interface Segregation Principle (ISP) in SOLID Design Principles?

The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. The…

2 years ago

What is Single Responsibility Principle (SRP) in SOLID Design Priciples?

The Single Responsibility Principle (SRP), also known as the Singularity Principle, is a software design…

2 years ago