57 lines
1.7 KiB
C#
57 lines
1.7 KiB
C#
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
|
|
|
/// <summary>A pin on one exact SDK materialization incarnation.</summary>
|
|
public interface IProjectedNodePin : IDisposable { bool IsValid { get; } }
|
|
|
|
/// <summary>Atomically fences idle retirement against new demand.</summary>
|
|
public sealed class ProjectedNodeLifetime
|
|
{
|
|
private readonly object _sync = new();
|
|
private int _pins;
|
|
private bool _retired;
|
|
private Action? _drained;
|
|
public bool TryPin(out IProjectedNodePin? pin)
|
|
{
|
|
lock (_sync)
|
|
{
|
|
if (_retired) { pin = null; return false; }
|
|
checked { _pins++; }
|
|
pin = new Pin(this);
|
|
return true;
|
|
}
|
|
}
|
|
public bool TryRetire()
|
|
{
|
|
lock (_sync) { if (_retired || _pins != 0) return false; _retired = true; return true; }
|
|
}
|
|
public void ForceRetire() => ForceRetire(null);
|
|
internal void ForceRetire(Action? drained)
|
|
{
|
|
Action? ready = null;
|
|
lock (_sync)
|
|
{
|
|
_retired = true;
|
|
_drained += drained;
|
|
if (_pins == 0) { ready = _drained; _drained = null; }
|
|
}
|
|
ready?.Invoke();
|
|
}
|
|
public bool IsActive { get { lock (_sync) return !_retired; } }
|
|
private void Release()
|
|
{
|
|
Action? ready = null;
|
|
lock (_sync)
|
|
{
|
|
_pins--;
|
|
if (_retired && _pins == 0) { ready = _drained; _drained = null; }
|
|
}
|
|
ready?.Invoke();
|
|
}
|
|
private sealed class Pin(ProjectedNodeLifetime owner) : IProjectedNodePin
|
|
{
|
|
private int _disposed;
|
|
public bool IsValid => Volatile.Read(ref _disposed) == 0 && owner.IsActive;
|
|
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) owner.Release(); }
|
|
}
|
|
}
|