using System.Threading;
using WIDESEAWCS_S7Simulator.Core.Interfaces;
namespace WIDESEAWCS_S7Simulator.Core.Memory
{
///
/// 内存区域基类
///
public abstract class MemoryRegion : IMemoryRegion
{
///
/// 内存数据
///
protected readonly byte[] _memory;
///
/// 读写锁(支持并发访问)
///
protected readonly ReaderWriterLockSlim _lock;
///
/// 区域类型
///
public abstract string RegionType { get; }
///
/// 区域大小(字节)
///
public int Size { get; }
///
/// 构造函数
///
/// 区域大小
protected MemoryRegion(int size)
{
Size = size;
_memory = new byte[size];
_lock = new ReaderWriterLockSlim();
}
///
/// 读取字节数据
///
public virtual byte[] Read(ushort offset, ushort length)
{
_lock.EnterReadLock();
try
{
if (offset + length > Size)
throw new ArgumentOutOfRangeException(
$"读取超出{RegionType}区范围: offset={offset}, length={length}, size={Size}");
byte[] result = new byte[length];
Array.Copy(_memory, offset, result, 0, length);
return result;
}
finally
{
_lock.ExitReadLock();
}
}
///
/// 写入字节数据
///
public virtual void Write(ushort offset, byte[] data)
{
_lock.EnterWriteLock();
try
{
if (offset + data.Length > Size)
throw new ArgumentOutOfRangeException(
$"写入超出{RegionType}区范围: offset={offset}, length={data.Length}, size={Size}");
Array.Copy(data, 0, _memory, offset, data.Length);
}
finally
{
_lock.ExitWriteLock();
}
}
///
/// 清空区域
///
public virtual void Clear()
{
_lock.EnterWriteLock();
try
{
Array.Clear(_memory, 0, Size);
}
finally
{
_lock.ExitWriteLock();
}
}
///
/// 释放资源
///
public virtual void Dispose()
{
_lock?.Dispose();
}
}
}