Is a bool read/write atomic in C#

dbkk picture dbkk · Sep 12, 2008 · Viewed 56.1k times · Source

Is accessing a bool field atomic in C#? In particular, do I need to put a lock around:

class Foo
{
   private bool _bar;

   //... in some function on any thread (or many threads)
   _bar = true;

   //... same for a read
   if (_bar) { ... }
}

Answer

Larsenal picture Larsenal · Sep 12, 2008

Yes.

Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types.

as found in C# Language Spec.

Edit: It's probably also worthwhile understanding the volatile keyword.