What operations are atomic in C#?

Eric picture Eric · Jul 31, 2012 · Viewed 27.8k times · Source

Is there a systematic way to know whether an operation in C# will be atomic or not? Or are there any general guidelines or rules of thumb?

Answer

Peter Ritchie picture Peter Ritchie · Jul 31, 2012

For something more complete/detailed:

Reads and writes to 32-bit value types are atomic: This includes the following intrinsic value (struct) types: bool, char, byte, sbyte, short, ushort, int, uint, float. The following types (amongst others) are not guaranteed to be atomic: decimal, double, long, ulong.

e.g.

int x;
x = 10; // atomic
decimal d;

d = 10m; // not atomic

Reference assignment is also an atomic operation:

private String _text;
public void Method(String text)
{
  _text = text; // atomic
}