3 ms·
So from I'm understanding here, the volatile keyword makes sure that the code always has the latest value when it is read by a thread. Otherwise, you might get
by Maultasche 11y ago
So from I'm understanding here, the volatile keyword makes sure that the code always has the latest value when it is read by a thread. Otherwise, you might get a cached value.
A lock, on the other hand, does the same thing, but goes further in preventing other threads from changing the value while the lock is in place.
So the volatile keyword seems to be great for read-only operations on data shared between threads, but won't prevent a race condition if the same code that is reading the data is also updating the value. A lock would be necessary for that.
Interesting. I knew about volatile in C++, but I wasn't aware that C# had a volatile as well.