The best way to prevent code removal is to use the code.
if you are worries about optimizing the while loop in your example
class Test
{
long foo;
static void Main()
{
var test = new Test();
new Thread(delegate() { Thread.Sleep(500); test.foo = 255; }).Start();
while (test.foo != 255) ;
Console.WriteLine("OK");
}
}
you still could use volatile to do this by modifying your while loop
volatile int temp;
//code skipped in this sample
while(test.foo != 255) { temp = (int)foo;}
Now assuming you are SURE you won't have any thread safety issues. you are using your long foo so it won't be optimized away. and you don't care about losing any part of your long since you are just trying to keep it alive.
Make sure you mark your code very clearly if you do something like this. possibly write a VolatileLong class that wraps your long (and your volatile int) so other people understand what you are doing
also other thread-safty tools like locks will prevent code removal. for example the compiler is smart enough not to remove the double if in the sinleton pattern like this.
if (_instance == null) {
lock(_lock) {
if (_instance == null) {
_instance = new Singleton();
}
}
}
return _instance;