Search code examples
c#.netmultithreadingatomic

What operations are atomic in C#?


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?


Solution

  • 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
    }