From be2b6021558fb64a5d1bbdb9358e21a239d64fa8 Mon Sep 17 00:00:00 2001 From: Martin Zikmund Date: Sat, 6 Jun 2020 13:33:41 +0200 Subject: [PATCH] feat: StartStopEventWrapper --- src/Uno.UWP/Helpers/StartStopEventWrapper.cs | 50 ++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/Uno.UWP/Helpers/StartStopEventWrapper.cs diff --git a/src/Uno.UWP/Helpers/StartStopEventWrapper.cs b/src/Uno.UWP/Helpers/StartStopEventWrapper.cs new file mode 100644 index 000000000000..6c994ffb1b8e --- /dev/null +++ b/src/Uno.UWP/Helpers/StartStopEventWrapper.cs @@ -0,0 +1,50 @@ +using System; + +namespace Uno.Helpers +{ + internal class StartStopEventWrapper + where TDelegate : Delegate + { + private readonly object _syncLock = new object(); + private readonly Action _onFirst; + private readonly Action _onLast; + + public StartStopEventWrapper( + Action onFirst, + Action onLast) + { + _onFirst = onFirst; + _onLast = onLast; + } + + public TDelegate Event { get; private set; } = null; + + public void AddHandler(TDelegate handler) + { + lock (_syncLock) + { + var firstSubscriber = Event == null; + Event = (TDelegate)Delegate.Combine(Event, handler); + if (firstSubscriber) + { + _onFirst(); + } + } + } + + public void RemoveHandler(TDelegate handler) + { + lock (_syncLock) + { + if (Event != null) + { + Event = (TDelegate)Delegate.Remove(Event, handler); + if (Event == null) + { + _onLast(); + } + } + } + } + } +}