When should the volatile keyword be used in C#?

前端 未结 10 963
盖世英雄少女心
盖世英雄少女心 2020-11-22 12:04

Can anyone provide a good explanation of the volatile keyword in C#? Which problems does it solve and which it doesn\'t? In which cases will it save me the use of locking?

10条回答
  •  没有蜡笔的小新
    2020-11-22 12:38

    The compiler sometimes changes the order of statements in code to optimize it. Normally this is not a problem in single-threaded environment, but it might be an issue in multi-threaded environment. See following example:

     private static int _flag = 0;
     private static int _value = 0;
    
     var t1 = Task.Run(() =>
     {
         _value = 10; /* compiler could switch these lines */
         _flag = 5;
     });
    
     var t2 = Task.Run(() =>
     {
         if (_flag == 5)
         {
             Console.WriteLine("Value: {0}", _value);
         }
     });
    

    If you run t1 and t2, you would expect no output or "Value: 10" as the result. It could be that the compiler switches line inside t1 function. If t2 then executes, it could be that _flag has value of 5, but _value has 0. So expected logic could be broken.

    To fix this you can use volatile keyword that you can apply to the field. This statement disables the compiler optimizations so you can force the correct order in you code.

    private static volatile int _flag = 0;
    

    You should use volatile only if you really need it, because it disables certain compiler optimizations, it will hurt performance. It's also not supported by all .NET languages (Visual Basic doesn't support it), so it hinders language interoperability.

提交回复
热议问题