C# Keywords Tutorial Part 98: volatile

C# Keywords Tutorial Part 98: volatile

A number of characteristics in the popular programming language C# enable programmers to create dependable and resilient programs. The “volatile” keyword, which is used to guarantee thread-safety in multi-threaded programs, is one of these characteristics. This blog article will go into great depth on the “volatile” keyword and give C# use examples.

The “volatile” Keyword in C#

The “volatile” keyword is used to indicate that a field or variable may be modified by multiple threads and that the compiler should not perform optimizations that could affect the order of access to that field or variable. By default, the compiler may reorder instructions to optimize performance, which can lead to unexpected behavior in multi-threaded applications.

When a variable is declared as “volatile,” the compiler is informed that the variable can be modified by multiple threads, and as a result, it generates the necessary machine code to ensure that changes to the variable are immediately visible to all threads. This ensures that any changes made to the variable are immediately visible to all other threads, and there is no possibility of reading stale data.

The following is an example of declaring a volatile field in C#:

class MyClass
{
    public volatile int MyField;
}

In this example, the “MyField” field is declared as volatile. This means that any changes made to “MyField” will be immediately visible to all threads accessing it.

Example of Using the “volatile” Keyword in C#

To illustrate how the “volatile” keyword can be used in a multi-threaded application, let’s consider the following example:

class Program
{
    private volatile bool _shouldStop;

    static void Main(string[] args)
    {
        var program = new Program();

        new Thread(program.Run).Start();

        Console.ReadKey();

        program._shouldStop = true;
    }

    void Run()
    {
        while (!_shouldStop)
        {
            Console.WriteLine("Running...");
            Thread.Sleep(1000);
        }
    }
}

To control a loop in the “Run” function, we define a private volatile boolean field called “_shouldStop” in this example. The “Run” method is started by the “Main” function, which then waits for a key hit before closing the thread. The “_shouldStop” property is set to true when a key is depressed, ending the loop in the “Run” method.

We guarantee that any changes made to the “_shouldStop” field in one thread are instantly visible to all other threads accessing it by designating it as volatile. As a result, there is no chance of the thread accessing stale data because the loop in the “Run” function will instantly end when the “_shouldStop” parameter is set to true.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *