“Link to unstable field will not be considered as volatile” consequences

Following code

using System.Threading; class Test { volatile int counter = 0; public void Increment() { Interlocked.Increment(ref counter); } } 

Raises the following compiler warning:

 "A reference to a volatile field will not be treated as volatile" 

Am I doing something wrong here to raise this warning? Why does the compiler warn me about this?

+38
multithreading c # volatile
Jan 08 '09 at 17:24
source share
4 answers

You are not doing anything wrong. According to the documentation :

An unstable field usually should not be passed using the ref or out parameter, because it will not be considered as mutable within the function. There are exceptions to this, for example, when calling an interconnected API.

+39
Jan 08 '09 at 17:29
source share

Basically the warning is that when you pass the volatile field by reference, the calling code does not know to handle it in a volatile way. For Interlocked.Increment, which probably doesn't matter due to the nature of the method - but then you don't need a variable to be mutable anyway if you use Interlocked.

In general, I think that I would not mix the two - if you use Interlocked, do it everywhere (using Interlocked.CompareExchange(ref counter, 0, 0) to read it). I can’t say that I often use volatility, personally. For simple counters, I can use Interlocked, but I most likely use locking for most tasks.

+30
Jan 08 '09 at 17:28
source share

Use this:

  #pragma warning disable 420 // M // dM // MMr // 4MMML . // MMMMM. xf // . "MMMMM .MM- // Mh.. +MMMMMM .MMMM // .MMM. .MMMMML. MMMMMh // )MMMh. MMMMMM MMMMMMM // 3MMMMx. 'MMMMMMf xnMMMMMM" // '*MMMMM MMMMMM. nMMMMMMP" // *MMMMMx "MMMMM\ .MMMMMMM= // *MMMMMh "MMMMM" JMMMMMMP // MMMMMM 3MMMM. dMMMMMM . // MMMMMM "MMMM .MMMMM( .nnMP" // =.. *MMMMx MMM" dMMMM" .nnMMMMM* // "MMn... 'MMMMr 'MM MMM" .nMMMMMMM*" // "4MMMMnn.. *MMM MM MMP" .dMMMMMMM"" // ^MMMMMMMMx. *ML "M .M* .MMMMMM**" // *PMMMMMMhn. *x > M .MMMM**"" // ""**MMMMhx/.h/ .=*" // .3P"%.... // nP" "*MMnx if(Interlocked.CompareExchange(ref isLoaded, 1, 0) != 0) return; #pragma warning restore 420 
+25
Oct 02 '09 at 22:28
source share

You get an error because you are passing the field by reference. I think this means that the target method has no idea that the field is marked as volatile , and therefore will not consider it as such.

+3
Jan 08 '09 at 17:28
source share



All Articles