Powered by Blogger.

Saturday, March 1, 2014

Volatile keyword in C#.Net:



In this post we will discuss about volatile keyword in C#.Net.

Also check out:

- Encrypt and Decrypt a file in C#.Net

- Jagged arrays in C#.Net

- sys.objects type in SQL Server 2008

The volatile keyword indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.

The system always reads the current value of a volatile object at the point it is requested, even if the previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment.

The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread.

The volatile modifier can be used  only with the following types : 
- Any reference type.
- Any pointer type .
- The types sbyte, byte, short, ushort, int, uint, char, float, bool.
- An enum type with an enum base type of byte, sbyte, short, ushort, int, or uint.

Example Code 
using System;
using System.Threading;
class volatile_Test
{
   public static string result;  
   public static volatile bool done;
   static void m1() {
      result = “This is sample data”;  
      done = true;
   }
   static void Main() {
      done = false;
      // Run m1() in a new thread
      new Thread(new ThreadStart(m1)).Start();
      // Wait for m1 to signal that it has a result by setting
      // finished to true.
     
         if (done) {
            Console.WriteLine("result = {0}", result);
            return;
          }
   }
}

In this example, the method Main starts a new thread running the method m1. This method stores a  string value into a non-volatile field called result, then stores true in the volatile field done. The main thread waits for the field done to be set to true, then reads the string result. Since done has been declared volatile, the main thread must read the string "This is sample data" from the field result. If the field done had not been declared volatile, then it would be permissible for the store to result to be visible to the main thread after the store to done, and hence for the main thread to read the  null value  from the field result. Declaring done as a volatile field prevents any such inconsistency.



0 comments

Post a Comment