I have a variable that I use to represent state. It can be read and written from multiple streams.
I use Interlocked.Exchange and Interlocked.CompareExchange to change it. However, I read it from multiple threads.
I know that volatile can be used to make sure that a variable is not cached locally, but is always read directly from memory.
However, if I set the variable to volatile, then it generates a warning about using volatile and passing using ref to Interlocked.
I want each thread to read the last value of a variable, not some cached version, but I cannot use volatile.
There is Interlocked.Read , but it is designed for 64-bit types and is not available in a compact structure. The documentation for it says that it is not needed for 32-bit types, since they are already performed in one operation.
There are statements on the Internet that you do not need volatility if you use blocking methods for all of your access. However, you cannot read a 32-bit variable using Interlocked methods, so you cannot use Interlocked methods for all of your access.
Is there a way to safely read and write my variable without using a lock?
trampster Jul 27 '09 at 5:06 2009-07-27 05:06
source share