You read too much theory. Yes, this can happen in practice if another thread
Console.WriteLine("a: {0}, b: {1}", a, b);
Since String.Format, which is used to format the string, has a signature
String Format(string fmt, params object[] args) { .... }
your integers will be copied due to boxing. The only condition that must be true is that the time slice of the threads ends when it has copied a in its unified state. Later, when the thread resumes, both variables are set to one, but your console output will be
a: 0, b: 1
The point of view of other values ββoccurs immediately if you work with copies of the values ββwithout realizing it. It is for this reason that you usually allow other people to write the correct code without blocking. If you try to debug unlocked code using Console.WriteLine, I wish you the best of luck.
Although a and b are set in order (I don't think the JIT compiler will change your blocked calls), you have no guarantee that other threads will see only two zeros or two. You could try to read b first and see if it matters, then you can print the value of a, but in this case you don't even need the value of any. This should be true, at least for the x86 memory model. This assumption may be violated by weaker memory models such as ARM.
source share