Home
C#
volatile Example
Updated Dec 24, 2024
Dot Net Perls
Volatile. This modifier reduces concurrency issues. Compilers reorder instructions in blocks. This improves performance but causes problems for concurrent threads.
Keyword notes. Volatile provides a way to affect how the compiler optimizes accesses to a field. It can fix certain kinds of bugs in threaded programs.
lock
Example. This example would function correctly without the volatile modifier. It illustrates the concept of the volatile keyword, not to provide a real-world example.
Next There are 2 static fields. One is an object reference of string type. The other is a volatile bool value type.
Then In the Main method, a new thread is created, and the SetVolatile method is invoked. In SetVolatile, both the fields are set.
ThreadStart
using System;
using System.Threading;

class Program
{
    static string _result;
    static volatile bool _done;

    static void SetVolatile()
    {
        // Set the string.
        _result = "Dot Net Perls";
        // The volatile field must be set at the end of this method.
        _done = true;
    }

    static void Main()
    {
        // Run the above method on a new thread.
        new Thread(new ThreadStart(SetVolatile)).Start();

        // Wait a while.
        Thread.Sleep(200);

        // Read the volatile field.
        if (_done)
        {
            Console.WriteLine(_result);
        }
    }
}
Dot Net Perls
Program info. Why is the bool volatile? First, the logic in this program is correct even without the volatile modifier on the bool.
Detail Compilers introduce extra, hidden complexity—they use a lot of optimizations.
And Some of these optimizations reorder loads and stores from variables. So conceptually the program could be incorrect.
Thus The order of assignments could change. When multiple threads execute at once, this can cause serious problems.
Detail Volatile tells the compiler not to change the order of accesses to the field.
Flags. The example demonstrates a volatile field used as a flag. The bool type is commonly used as a flag. So when the flag is set to true, you can take other action on that variable.
Summary. Volatile restrict the optimizations the compiler makes regarding loads and stores into the field. This helps threaded programs.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 24, 2024 (simplify).
Home
Changes
© 2007-2025 Sam Allen