Is there some practical reason why the .NET team decided not to support Boolean in Interlocked.Exchange operation?
One of the usage examples is when you want to guarantee that some code is executed only once and you want to use a Boolean flag for that.
The Interlocked class provides a number of static methods that perform atomic operations. These can generally be regarded as thread-safe.
Interlock. Exchange returns the original value while performing an atomic operation. The whole point is to provide a locking mechanism. So it is actually two operations: read original value and set new value. Those two together are not atomic.
The default value of the bool type is false .
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.
Yes, there is a good reason. The implementation of the Interlocked methods requires low-level support at the processor level. See this answer for example. That's an issue when you define a framework that's architecture agnostic.
Implementing the low-lock techniques supported by the Interlocked class on data types that are a fraction of the native processor word size is difficult. The RISC approach to cpu design that was popular 10+ years ago discouraged it strongly. The mismatch between operand size and native memory bus width makes it very hard to implement. One reason that Intel's x86 architecture is still on your lap, surviving 30 years already by not taking the shortcuts. More background info on RISC in this wikipedia article.
Not answering the question, but as a workaround you can just use int instead of bool the way C does.
int m_IsFirstTime = 1; // 1 means true 0 means false. void SomeMethod() { if (1 == Interlocked.Exchange(ref m_IsFirstTime , 0)) // Do something for the first time. else // Do something for all other times. }
P.S. If there is evidence that read is faster than write then Interlocked.CompareExchange might be better for this case (only one first time and I assume a lot of non first).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With