I just want to do a simple, though thread-safe, boolean test (and set) so:
if(myBoolean==false) //should not lock/wait!
{
myBoolean=true;
.....
}
else
{
....
}
I considered the following (although possibly incorrectly, so please correct me where I misunderstood)
Anyone have an idea what is the class/construct to do this in an efficient manner?
Consider Interlocked.CompareExchange.
The answer (Interlocked.CompareExchange
) was already given, but here's my usage example:
private int _isDisposing;
public bool IsDisposing
{
get
{
return this._isDisposing != 0;
}
}
public void Dispose()
{
// Side note: I may want to `return` instead of `throw`
if (Interlocked.CompareExchange(ref _isDisposing, 1, 0) != 0)
throw new InvalidOperationException("Dispose was recursively called.");
try
{
Dispose(true);
GC.SuppressFinalize(this);
}
finally
{
_isDisposing = 0;
}
}
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