Is a bool read/write atomic in C#
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.
As stated above bool is atomic but you still need to remeber that it also depends on what you want to do with it.
if(b == false)
{
//do something
}
is not an atomic operation meaning that b value could change before the current thread executes the code after the if statement.
bool accesses are indeed atomic, but that isn't the whole story.
You don't have to worry about reading a value that is 'incompletely written' - it isn't clear what that could possibly mean for a bool in any case - but you do have to worry about processor caches, at least if details of timing are an issue. If thread #1 running on core A has your _bar
in cache, and _bar
gets updated by thread #2 running on another core, thread #1 will not see the change immediately unless you add locking, declare _bar
as volatile
, or explicitly insert calls to Thread.MemoryBarrier()
to invalidate the cached value.