Pages

Thursday, March 29, 2012

What is volatile keyword in C#

volatile

The keyword volatile means that a field can be modified in the program by thinks along the lines of say the operating system, hardware or even a thread executing concurrently. General syntax of volatile is:


volatile declaration
where:

declaration is of a field.

Key Points:

Whenever a volatile is requested, the system returns the current value at the time of the request. All assignments are written to the object immediately.

Common usage of the volatile modifier is when a particular field is accessed by many threads without using the lock statement to serialize access. So in essence the volatile modifier guarantees that a thread will retrieve the most recent value written by another thread (even if it was modified by the previous instruction from you call).

You are not allowed to use volatile on just any time. The following is a list of types you can implement this modifier on:

  • Any reference type.
  • Any pointer type in a unsafe context
  • sbyte, byte, short, ushort, int, uint, char, float, bool.
  • An enum type with an enum base type of the following: byte, sbyte, short, ushort, int, uint.
Example:

public volatile int iAge;

No comments: