The following code:
while (x == 1) { ... }
might be optimized to
while (true) { ... }
if x
gets assigned in another thread only. See Illustrating usage of the volatile keyword in C# . The answer there solves this by setting x
to be volatile
.
However, it looks like that is not the correct way to go about it according to these three contributors (with a combined reputation of over 1 million :) )
Hans Passant A reproducable example of volatile usage : "never assume that it is useful in a multi-threading scenario."
Marc Gravell Value of volatile variable doesn't change in multi-thread : "volatile is not the semantic I usually use to guarantee the behavior"
Eric Lippert Atomicity, volatility and immutability are different, part three : "I discourage you from ever making a volatile field."
Assuming a Backgroundworker
is treated like any other multithreading (as opposed to having some built-in mechanism to prevent optimization) - How can bad-optimization be prevented?