What to use instead of Interlocked.Equals

I have legacy code that uses Interlocked.Equals to compare values. Values ​​can be two types of bool or can compare an array of structures with NULL. Resharper complains about Interlocked.Equals saying "access to a static member of a type through a derived type". I know that Equals is not a member of the Interlocked class, but rather is a member of the object class. The comparison takes place in the stream, so I assume that the source encoder wanted to perform the comparison as an atomic operation, therefore, using a lock. Since object.Equals is not atomic, what is the correct, thread safe, way to make such comparisons? Note that most of the data is static, some of them are static unstable.

+3
source share
2 answers

Single reads of Boolean or object references are atomic. So, if you are comparing one common value with a constant or local variable, no "lock" is required. As John said, you will need to use Interlocked.CompareExchangeit to make sure you read the last value if the shared variables are not volatile.

If both mappings are separate, then you will need the actual lock. There is no way to atomically compare two common AFAIK values.

Update:

I recommend explicit blocking for shared data. Keep in mind that the source code has been completely broken, so feel free to change it.

, ? ; , . , , -.

+5

, , . , . , , , , , - , . //, , .

Interlocked.CompareExchange, , .

? (, ), ( , , ).

+6

Source: https://habr.com/ru/post/1755532/


All Articles