using System.Threading;
|
using WIDESEAWCS_S7Simulator.Core.Interfaces;
|
|
namespace WIDESEAWCS_S7Simulator.Core.Memory
|
{
|
/// <summary>
|
/// 内存区域基类
|
/// </summary>
|
public abstract class MemoryRegion : IMemoryRegion
|
{
|
/// <summary>
|
/// 内存数据
|
/// </summary>
|
protected readonly byte[] _memory;
|
|
/// <summary>
|
/// 读写锁(支持并发访问)
|
/// </summary>
|
protected readonly ReaderWriterLockSlim _lock;
|
|
/// <summary>
|
/// 释放状态标志
|
/// </summary>
|
protected bool _disposed = false;
|
|
/// <summary>
|
/// 区域类型
|
/// </summary>
|
public abstract string RegionType { get; }
|
|
/// <summary>
|
/// 区域大小(字节)
|
/// </summary>
|
public int Size { get; }
|
|
/// <summary>
|
/// 构造函数
|
/// </summary>
|
/// <param name="size">区域大小</param>
|
protected MemoryRegion(int size)
|
{
|
Size = size;
|
_memory = new byte[size];
|
_lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
|
}
|
|
/// <summary>
|
/// 读取字节数据
|
/// </summary>
|
public virtual byte[] Read(ushort offset, ushort length)
|
{
|
if (_disposed)
|
throw new ObjectDisposedException(nameof(MemoryRegion));
|
|
_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();
|
}
|
}
|
|
/// <summary>
|
/// 写入字节数据
|
/// </summary>
|
public virtual void Write(ushort offset, byte[] data)
|
{
|
if (_disposed)
|
throw new ObjectDisposedException(nameof(MemoryRegion));
|
|
if (data == null)
|
throw new ArgumentNullException(nameof(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();
|
}
|
}
|
|
/// <summary>
|
/// 清空区域
|
/// </summary>
|
public virtual void Clear()
|
{
|
if (_disposed)
|
throw new ObjectDisposedException(nameof(MemoryRegion));
|
|
_lock.EnterWriteLock();
|
try
|
{
|
Array.Clear(_memory, 0, Size);
|
}
|
finally
|
{
|
_lock.ExitWriteLock();
|
}
|
}
|
|
/// <summary>
|
/// 释放资源
|
/// </summary>
|
public void Dispose()
|
{
|
Dispose(true);
|
GC.SuppressFinalize(this);
|
}
|
|
/// <summary>
|
/// 释放资源
|
/// </summary>
|
/// <param name="disposing">是否正在释放托管资源</param>
|
protected virtual void Dispose(bool disposing)
|
{
|
if (!_disposed)
|
{
|
if (disposing)
|
{
|
_lock?.Dispose();
|
}
|
_disposed = true;
|
}
|
}
|
}
|
}
|