using DotNext.IO.MemoryMappedFiles; using SharedMemory; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace WriterApp; /// /// A that creates no events, so that the lifetime of the shared memory /// can be tested apart from the lifetime of named events. Compiled into the tests and the peer. /// public class SharedBuffer : BufferReadWrite where T : struct { public SharedBuffer(string name, int length) : base(name, length * Unsafe.SizeOf()) { } public SharedBuffer(string name) : base(name) { } /// /// Prevents write operations from deadlocking by throwing a TimeoutException if the WriteWaitEvent is not available within milliseconds /// private void WriteWait() { if (!WriteWaitEvent.WaitOne(ReadWriteTimeout)) throw new TimeoutException("The write operation timed out waiting for the write lock WaitEvent. Check your usage of AcquireWriteLock/ReleaseWriteLock and AcquireReadLock/ReleaseReadLock."); } /// /// Prevents read operations from deadlocking by throwing a TimeoutException if the ReadWaitEvent is not available within milliseconds /// private void ReadWait() { if (!ReadWaitEvent.WaitOne(ReadWriteTimeout)) throw new TimeoutException("The read operation timed out waiting for the read lock WaitEvent. Check your usage of AcquireWriteLock/ReleaseWriteLock and AcquireReadLock/ReleaseReadLock."); } private Span ByteSpan { get { return Mmf.CreateDirectAccessor(BufferOffset, BufferSize).Bytes; } } private Span DataSpan { get { var spanT = MemoryMarshal.Cast(ByteSpan); return spanT; } } public void Write(T[] array) { WriteWait(); var span = DataSpan; if (span.Length < array.Length) throw new ArgumentException($"The array length {array.Length} is greater than the buffer length {span.Length}"); array.AsSpan().CopyTo(span); } public void Read(T[] array) { ReadWait(); var span = DataSpan; if (span.Length > array.Length) throw new ArgumentException($"The array length {array.Length} is less than the buffer length {span.Length}"); span.CopyTo(array.AsSpan()); } public void Write(ReadOnlySpan span) { WriteWait(); var dataSpan = DataSpan; if (dataSpan.Length < span.Length) throw new ArgumentException($"The span length {span.Length} is greater than the buffer length {dataSpan.Length}"); span.CopyTo(dataSpan); } public void Read(Span span) { ReadWait(); var dataSpan = DataSpan; if (dataSpan.Length > span.Length) throw new ArgumentException($"The span length {span.Length} is less than the buffer length {dataSpan.Length}"); dataSpan.CopyTo(span); } public void BufferAction(Action> action) { ReadWait(); var dataSpan = DataSpan; action(dataSpan); } public T First => DataSpan[0]; }