I read quite a few posts on this subject, and I think I finally understood how the volatile keyword works in C #. However, I wanted to ask here to make sure that I understand the concepts correctly. Consider the following code:
class ThreadWrapper { public bool Enabled { get; set; } private void ThreadMethod() { while (Enabled) {
From what I understand, if another thread had to set Enabled=false , the original thread might not see this change right away (or maybe someday?). To ensure that the compiler does not optimize access to the Enabled property and relies on cached values, changing the code as follows should fix the situation.
public bool Enabled { get {return mEnabled;} set {mEnabled=value;} } private volatile bool mEnabled;
Now that the Enabled value is read, it is guaranteed to get its most current value, right? If so, I should be able to use it as a simple signal or flag (for example, I am above).
As another example, consider the following:
class C { private volatile int i; private volatile bool enabledA; private volatile bool enabledB; void ThreadA() { i = 0;
For simple cross-threading, for example, is volatile satisfactory here? I understand that i++ not an atomic operation, but if one thread does all the increment and the other just wants to read it to see if it reaches a certain threshold, are we okay?
Edit: Of course, I found another similar question with detailed answers after the fact.