I want to create boolean flag that is both thread-safe and non-blocking on both 32 bit and 64 bit systems. Does this solution satisfy those 2 requirements? If not, what will?
public bool Flag {
get {
return Interlocked.Read( ref _flag ) == 1;
}
set {
if ( value ) {
// set flag to "true" if it's false
Interlocked.CompareExchange( ref _flag, 1, 0 );
}
else {
// set flag to "false" if it's true
Interlocked.CompareExchange( ref _flag, 0, 1 );
}
}
}
private Int32 _flag;
(edited) to use Int32
via. @M.kazemAkhgary
Example: 3 timers, each with intentionally overlapping tick intervals for this example. 2 timer callbacks are reading the flag. 1 timer callback reads and writes to the flag.
// Inline function
void Callback( object msg ) {
if ( Flag ) Debug.WriteLine( (string) msg );
}
// Checks Flag
var timer1 = new Timer(
Callback,
"Tick", // callback arg
0, // start timer now
100 // callback interval ms
);
// Checks Flag
var timer2 = new Timer(
Callback,
"Tock", // callback arg
0, // start timer now
20 // callback interval ms
);
// Toggles Flag every second
var timer3 = new Timer(
_ => {
Flag = !Flag;
},
null, // callback arg
0, // start timer now
1000 // callback interval ms
);