Namespace Eco.Shared.Concurrent
Classes
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).
ReadWriteSpinSemaphore
Very lightweight semaphore-like synchronization object based on System.Threading.SpinWait. It optimized for very-short write operations and concurrent read operations (short enough). It may spent lot of CPU cycles if you don't follow this rule. To achieve this internal state maintained which may be (-1 - for write operation in progress, 0 - for no operations, positive - for read operations). When positive it is equal to number of active read operations. WaitWrite() should be used for write operations and it will await when Eco.Shared.Concurrent.ReadWriteSpinSemaphore.state is 0 to switch state to -1. When write operation finished ReleaseWrite() should be used to allow other write and read operations. WaitRead() should be used for read operations and it will await until Eco.Shared.Concurrent.ReadWriteSpinSemaphore.state is greater or equal to 0 (no write operations in progress) and then increases state value. When read operation finished ReleaseRead() should be used to allow write operations. WARNING! Because this is a struct you should never ever copy it and always as an class field only. Read more in System.Threading.SpinLock documentation (https://docs.microsoft.com/en-us/dotnet/api/System.Threading.SpinLock?view=net-7.0).
ReadWriteSpinSemaphoreExtensions
Set of extension methods for ReadWriteSpinSemaphore.
ReadWriteSpinSemaphoreExtensions.ReadWriteSpinSemaphoreRead
Disposable Read operation for DisposableRead(ref ReadWriteSpinSemaphore) method.
ReadWriteSpinSemaphoreExtensions.ReadWriteSpinSemaphoreWrite
Disposable Write operation for DisposableWrite(ref ReadWriteSpinSemaphore) method.
SpinLockSection
Helper struct to avoid boilerplate with System.Threading.SpinLock. Only available for .NET 7.0+ and C# 11+. Normally you need to use following code:
bool lockTaken = false;
try
{
spinLock.Enter(ref lockTaken);
DoWithLock();
}
finally
{
if (lockTaken)
spinLock.Exit();
}
but using SpinLockSection can simplify to
using (spinLock.EnterDisposableLock())
DoWithLock();
SpinLockSectionExtensions
Extension methods set for SpinLockSection.