The volatile keyword indicates that a field might be modified by multiple concurrently executing threads. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.
The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock Statement (C# Reference) statement to serialize access. See How to: Create and Terminate Threads (C# Programming Guide) for an example of volatile in a multi-threaded scenario.
The volatile keyword can be applied to fields of these types:
-
Reference types.
-
Pointer types (in an unsafe context). Note that while the pointer itself can be volatile, the object that it points to cannot. In other words, you cannot declare a "pointer to volatile."
-
Integral types such as sbyte, byte, short, ushort, int, uint, char, float, and bool.
-
An enum type with an integral base type.
-
Generic type parameters known to be reference types.
The volatile keyword can only be applied to fields of a class or struct. Local variables cannot be declared volatile.
The following example shows how to declare a public field variable as volatile.
// csharp_volatile.cs
// compile with: /target:library
class Test
{
public volatile int i;
Test(int _i)
{
i = _i;
}
}
For more information, see the following sections in the C# Language Specification:
-
3.10 Execution order
-
10.4.3 Volatile fields
Reference
C# KeywordsModifiers (C# Reference)
Concepts
C# Programming GuideOther Resources
C# ReferenceFor example, if you had a thread continually updating the variable with the current value for the brightness of a live video image, any threads reading that variable would want to be sure that they used the latest value, not an old value held in a register.
Volatile ensures that the code goes back and re-reads the actual memory value.
I agree with Peter above in that the article is misleading and doesn't explain how optimized compiled code could misbehave when dealing with variables who's values could be changed outside of "nearby code" (i.e. another process, a hardware driver, another thread (esp. on multiproc) etc.)
Using your favorite search engine, lookup volatile cache c# and you'll get some further reading on this. Even Brad Abrams admits to learning something new about this keyword in his blog.
"The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement..."
This implies that volatile and lock are somewhat interchangeable. They are not. Simply declaring a member with volatile does not supersede need for "lock". volatile simply means that reads from and writes to occur directly to the member in the relative order in which they were written in the code. It doesn't stop a series of accesses to a volatile member from being preempted by another thread accessing the same member.