Atomicity of assignment can be achieved using System.Threading.Interlocked

 Interlocked.Exchange(ref toItem, fromItem); 

But how is it atomically to get an instance of a class atomically, because System.Threading.Interlocked does not have the Read(ref object) method, only Read(ref long) ?

 TObject obj = somethingObject; //Сомнение атомарности. //Поскольку передача указателя x64 не умещается в такт процессора, //и не гарантирует атомарности. 

please do not give examples with lock , since they are not interesting to me.

    1 answer 1

    The operation of reading an object reference is always atomic. This is a consequence of the basic principle of .NET: if your code does not contain unsafe calls, you can’t get an incorrect link to the object.

    As a result, reading int, pointers, and IntPtr are always atomic. Moreover, reading long is also atomically on a 64-bit system (the Interlocked.Read(ref long) method you found is intended for x86 or AnyCPU platforms)

    However, it must be understood that Interlocked operations are not only atomic, they are also memory barriers. Therefore, it is impossible to read a shared variable as TObject obj = somethingObject - this reading can give outdated data.

    To read you need to use the Volatile.Read method:

     TObject obj = Volatile.Read(ref somethingObject); 
    • Операция чтения ссылки на объект всегда атомарная Damn, this is logical! We have x64 IntPtr will only be on x64 application. Here I am stupid. - Dmitry Chistik
    • “For reading, you need to use the Volatile.Read method” judging by the documentation (MSDN), Volatile.Read guarantees only a memory barrier and no guarantees regarding the “old” data. In addition, to use V olatile.Read without Volatile.Write is simply useless, and in the example the author does not have suitable code for using this pair. - ixSci
    • The @ixSci memory barrier and the guarantee of data fatigue are the same, just the first term is formal, and the second is “on the fingers” - Pavel Mayorov
    • @ixSci what to record - something Interlocked.Exchange is quite a replacement for Volatile.Write - Pavel Mayorov
    • @PavelMayorov, let's be clear, i.e. You state that TObject obj = Volatile.Read(ref somethingObject); guaranteed to return the last value written to somethingObject ? If this is so, then you are mistaken, there is no such guarantee and the memory barrier does not give it. - ixSci