C# interlocked read example
Unfortunately, Interlocked. Read(ref value) only works if value is of type long. Consider the case that you're starting with an int field, which makes it impossible to use Interlocked. Read(), so you'll read the value directly instead since that's atomic anyway.These C# examples demonstrate the Interlocked type. Interlocked changes fields in a threadsafe way. c# interlocked read example
Interlocked instructions provide atomicity and interprocessor synchronization. Both writes and reads must be synchronized, so yes, you should be using interlocked instructions to read a value that is shared between threads and not protected by a lock.
Actually, I just looked at the BCL for Interlocked. cs. And it looks like Interlocked. Read for longs is literally just implemented with location, 0, 0). So I guess doing foo, 0, 0) for ints should be just fine. If there was an int Interlocked. Read, that's how it would have been implemented. The function both increments the counter and returns its value; the two operations are guaranteed to be atomic. Other interlocked functions exist for decrementingreading a counter, or adding toreading a variable.c# interlocked read example Using with a class. For example int i 5; (ref i, 10, 5); After this command, the int i would have a value 10. And also the compare and exchange happens atomically (single operation). When I tried using this with a class instance, the compare fails and the values are not exchanged.