37 lines
1.4 KiB
C#
37 lines
1.4 KiB
C#
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
|
|
|
/// <summary>Shared retained-candidate accounting across projected monitored items.</summary>
|
|
internal sealed class ProjectedCandidateBudget
|
|
{
|
|
private readonly object _sync = new();
|
|
private readonly int _maxEntries;
|
|
private readonly long _maxBytes;
|
|
private int _entries;
|
|
private long _bytes;
|
|
public ProjectedCandidateBudget(int maxEntries, long maxBytes)
|
|
{
|
|
if (maxEntries <= 0 || maxBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxEntries));
|
|
_maxEntries = maxEntries; _maxBytes = maxBytes;
|
|
}
|
|
public long RetainedBytes { get { lock (_sync) return _bytes; } }
|
|
public int RetainedEntries { get { lock (_sync) return _entries; } }
|
|
public bool TryReserve(long bytes, out IDisposable? lease)
|
|
{
|
|
lease = null;
|
|
if (bytes <= 0) return false;
|
|
lock (_sync)
|
|
{
|
|
if (_entries >= _maxEntries || bytes > _maxBytes - _bytes) return false;
|
|
_entries++; _bytes += bytes;
|
|
lease = new Reservation(this, bytes);
|
|
return true;
|
|
}
|
|
}
|
|
private void Release(long bytes) { lock (_sync) { _entries--; _bytes -= bytes; } }
|
|
private sealed class Reservation(ProjectedCandidateBudget owner, long bytes) : IDisposable
|
|
{
|
|
private int _released;
|
|
public void Dispose() { if (Interlocked.Exchange(ref _released, 1) == 0) owner.Release(bytes); }
|
|
}
|
|
}
|