Using Volatile

JJ TT 141 Reputation points
2020-12-07T14:58:02.367+00:00

Hello,

From you experience using syntax code volatile, what concrete example have you used volatile in your application and why?

(https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile)

Thank you!

.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,118 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Taylor 47,806 Reputation points
    2020-12-07T15:16:25.26+00:00

    The primary purpose of using volatile in C# is for multi-threading writes against a field.

       csharp  
       public static class SomeClass  
       {  
          public static long Id;  
       }  
    

    For performance reasons a processor can cache values it is reading into a register. As long as there are no writes then it is safe to cache into a register. However if the field is changed by another thread then the cached value is out of date. You can use a memory buffer to prevent this but that is generally only useful when your code is actually doing the writing. If you're just reading the value then using a memory buffer would effectively prevent a value from being cached and thus impact performance.

    The volatile keyword tells the runtime that it is possible for the value to be written in a thread other than the current thread and thus limits what optimizations that are done. It is a tradeoff between performance and safety.

    In general you should avoid using writable fields to begin with. This eliminates the need for volatile. You can learn more about volatile in the discussion of .NET memory model.

    0 comments No comments

  2. Xingyu Zhao-MSFT 5,356 Reputation points
    2020-12-08T07:24:36.767+00:00

    Hi @JJ TT ,

    When a thread interacts with the data in the cache, and the second thread attempts to read the same data at the same time, the second thread may read the obsolete version of the data from main memory. The volatile keyword can inform the compiler that the value of the variable should never be cached.

    Check the following reference.

    When should the volatile keyword be used in C#?

    Best Regards,
    Xingyu Zhao
    *
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments