using System; using System.Collections.Generic; namespace Avalonia.Remote.Protocol { class EventStash { private readonly IAvaloniaRemoteTransportConnection _transport; private readonly Action _exceptionHandler; private List _stash; private Action _delegate; public EventStash(IAvaloniaRemoteTransportConnection transport, Action exceptionHandler = null) { _transport = transport; _exceptionHandler = exceptionHandler; } public void Add(Action handler) { List stash; lock (this) { var needsReplay = _delegate == null; _delegate += handler; if(!needsReplay) return; lock (this) { stash = _stash; if(_stash == null) return; _stash = null; } } foreach (var m in stash) { if (_exceptionHandler != null) try { _delegate?.Invoke(_transport, m); } catch (Exception e) { _exceptionHandler(e); } else _delegate?.Invoke(_transport, m); } } public void Remove(Action handler) { lock (this) _delegate -= handler; } public void Fire(IAvaloniaRemoteTransportConnection transport, T ev) { if (_delegate == null) { lock (this) { _stash = _stash ?? new List(); _stash.Add(ev); } } else _delegate?.Invoke(_transport, ev); } } }