I have a variable which I am using to represent state. It can be read and written to from multiple threads.
I am using Interlocked.Exchange and Interlocked.CompareExchange to change it. However I am reading it from multiple threads.
I know that volatile can be used to make sure the variable is not cached locally but always reads directly from memory.
However if I set the variable to volatile then it generates a warning about using volatile and passing using ref to the Interlocked methods.
I want to ensure that each thread is reading the most recent value of the variable and not some cached version, but I can’t use volatile.
There is a Interlocked.Read but it is for 64 bit types and is not available on the compact framework. The documentation for it says that it is not needed for 32 bit types as they are already performed in a single operation.
There are statements made across the internet that you don’t need volatile if you are using the Interlocked methods for all your access. However you can’t read a 32 bit variable using the Interlocked methods, so there is no way you can use Interlocked methods for all your access.
Is there some way to accomplish the thread safe read and write of my variable without using lock?
You can safely disregard that warning when you’re using
Interlocked.Xxxfunctions (see this question), because they always do volatile operations. So avolatilevariable is perfectly OK for shared state. If you want to get rid of the warning at all costs, you actually can do an interlocked read withInterlocked.CompareExchange (ref counter, 0, 0).Edit: Actually, you need
volatileon your state variable only if you are going to write to it directly (i.e. not usingInterlocked.Xxx). As jerryjvl mentioned, reads of a variable updated with an interlocked (or volatile) operation will use the most recent value.