It is necessary to implement access (change / read) from threads to a common variable using the Interlocked class. Code snippets: Common variable:

string bufferMessage = "None"; 

Writing to variable:

 Interlocked.Exchange(ref bufferMessage, "Thread #" + threadName + " WRITE message: " + i); 

Reading:

 messagesRead.Add("Thread #" + threadName + " READ message: " + Interlocked.Read(ref bufferMessage)); 

Writing is successful, the compiler does not want to skip reading. Displays error:

 Не удается преобразовать из "ref string" в "ref long" 

Is it generally possible to read the value of a string variable using the Interlocked class?

  • one
    Interlocked.CompareExchange(ref bufferMessage, null, null) - PetSerAl

1 answer 1

The Read method is intended solely for reading 64-bit numbers ( long ) on 32-bit systems, since reading a 64-bit number on them is not an atomic operation.
Therefore, for both the string type and other double , float, and so on types in the Interlocked class, an explicit reading function does not exist.

Thanks @PetSerAl, as he noted correctly, you can atomically read the value using the CompareExchange method .

 Interlocked.CompareExchange(ref bufferMessage, null, null) 

This method will always return the value of the current bufferMessage variable, since bufferMessage != null (there is a comparison of the variable bufferMessage with 3 function arguments)