"are primitive data types in c# atomic (thread safe)?" Code Answer


there is no such thing as an atomic type. only operations can be atomic.

reading and writing a data type that fits into a single word (int on a 32-bit processor, long on a 64-bit processor) is technically "atomic", but the jitter and/or processor can decide to reorder instructions and thus create unexpected race conditions, so you either need to serialize access with lock, use the interlocked class for writes (and in some cases reads), or declare the variable volatile.

the short answer is: if two different threads may access the same field/variable and at least one of them will be writing, you need to use some sort of locking. for primitive types that's generally the interlocked class.

By Demplo on February 4 2022

Answers related to “are primitive data types in c# atomic (thread safe)?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.