Class ConcurrentFlag
This class is implementation of thread-safe flag which can be atomically set to true
with TrySet() method.
Once set the owning thread is responsible for call to Reset() method with returns value to false
if needed.
If this flag used as publicly available property then ensure it exposed as ref ConcurrentFlag Flag => ref this.flag
to avoid accidental struct copy
(in this case it will modify state of copy, not of the original flag).
Inheritance
Namespace: Eco.Shared.Concurrent
Assembly: Eco.Shared.dll
Syntax
public sealed class ConcurrentFlag : ValueType
Examples
Typical usage is following:
ConcurrentFlag doingSomething;
void DoSomething()
{
if (!doingSomething.TrySet())
return;
Something();
doingSomething.Reset();
}
It is replacement for boolean flag, but with thread-safety support. Equivalent non thread-safe code will look like:
bool doingSomething;
void DoSomething()
{
if (!doingSomething)
return;
doingSomething = true; // for multi-thread this flag may be already set by another thread here even if it wasn't in previous condition check
Something();
doingSomething = false;
}
Methods
Reset()
Resets flag to not set state. Should be called after successful TrySet() method if needed to make this flag available to be set again.
Declaration
public void Reset()
TrySet()
Tries atomically set flag. If this flag already set by another thread then the method returns false
.
Declaration
public bool TrySet()
Returns
Type | Description |
---|---|
System.Boolean |