Javatpoint Logo
Javatpoint Logo

Volatile Keyword in C#

When accessing member variables of a class or structure in multi-threaded situations, it is convenient to use the volatile keyword. The volatile keyword is used to indicate to the compiler that a variable may be accessed by more than one thread. When the C# compiler generates our code, it performs some optimizations. If a variable isn't tagged as volatile, the compiler will assume that only one thread will access it at a time.

Keep in mind that the volatile keyword can only be applied to the following kinds of data:

  • Reference types
  • Pointer types (in a risky situation). Be aware that while the object it points to can be volatile, the pointer itself cannot. Therefore, it is not possible to declare a "pointer to volatile".
  • types like char, float, sbyte, short, ushort, int, uint, and bool
  • the byte, sbyte, short, ushort, int, or uint base types of an enum type.
  • Known generic type parameters include IntPtr and UIntPtr, which are reference types.

Objects and structures that are variables will require the use of different locking techniques. A variable can only be declared as volatile if it belongs to a class or structure.

Simply include volatile as one of the variable modifiers to declare a variable as volatile.

The following example features two static fields. A string-type object reference makes up one field, and a volatile bool value type makes up the other. The SetVolatile method is called after a new thread is established in the Main method. Both of the fields are set in SetVolatile.

An example of how to use volatile fields in a multi-threading environment. The two static fields in this illustration are a volatile boolean flag and a reference to an integer array. The integer array is filled with data using the method, and the boole an flag is set to signify success. A new thread is established in the Main method to call the SetVolatile method, and we wait for a brief period of time before determining if the process has been completed. Finally, we output the integer array's contents.

Example:

Output:

Operation is complete. Resulting array:
1 2 3 4 5

It can lead to major issues when numerous threads run concurrently. It is important to note that the volatile modifier merely instructs the compiler to maintain the order of accesses to the field rather than forcing synchronisation of loads and stores. The code becomes more predictable from the standpoint of a programmer by removing reordering optimisations.

Again, since this is a complex C# concept, the most of you probably won't have to worry about utilising it, especially in ASP.NET. However, there have been times when we've utilized multithreading in an ASP.NET application (for screen scraping performance), so it's not wholly improbable that you might need to be familiar with multi-threaded programming.

Three portable uses for volatile after doing more research on the topic. Here is a summary of them.

  • Putting a local variable in a setjmp's scope to prevent it from rolling back after a
  • Memory that appears to have been altered by an outside source or because of a faulty memory mapping Signal handler mischief.
  • We also have an example where a worker thread is established and utilised to handle data concurrently with the main thread.

Another example showing how to manage a worker thread using a volatile flag. In this example, the Worker class runs some code in a loop until the shouldStop flag is set to true. The Worker class is created, a worker thread is started, and the Main procedure waits for the worker thread to become active before signalling it to cease.

Output:

Main thread: starting CustomWorker thread...
CustomWorker thread: working...
CustomWorker thread: working...
CustomWorker thread: working...
CustomWorker thread: working...
CustomWorker thread: working...
CustomWorker thread: terminating gracefully.
Main thread: CustomWorker thread has terminated.






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA