diff --git a/src/WeakEvent/WeakEvent.cs b/src/WeakEvent/WeakEvent.cs index 5bad7f7..bb53fbc 100644 --- a/src/WeakEvent/WeakEvent.cs +++ b/src/WeakEvent/WeakEvent.cs @@ -9,8 +9,15 @@ /// For more information, visit the GitHub repository. /// /// The type of the event argument. -public class WeakEvent : WeakEventBase +public class WeakEvent { + private readonly WeakEventCore _core = new(); + + /// + /// Number of living subscribers currently registered to the event. + /// + public int SubscriberCount => _core.SubscriberCount; + /// /// Subscribes the specified handler to the event. /// @@ -19,7 +26,7 @@ public class WeakEvent : WeakEventBase /// provided that the target is still alive. /// /// Thrown when is null. - public void Subscribe(Action handler) => base.SubscribeCore(handler); + public void Subscribe(Action handler) => _core.Subscribe(handler, WeakEventHandler.Create); /// /// Subscribes the specified async handler to the event. @@ -29,7 +36,7 @@ public class WeakEvent : WeakEventBase /// provided that the target is still alive. /// /// Thrown when is null. - public void Subscribe(Func handler) => base.SubscribeCore(handler); + public void Subscribe(Func handler) => _core.Subscribe(handler, WeakEventHandler.Create); /// /// Subscribes the specified async handler with a cancellation token to the event. @@ -39,28 +46,29 @@ public class WeakEvent : WeakEventBase /// provided that the target is still alive. /// /// Thrown when is null. - public void Subscribe(Func handler) => base.SubscribeCore(handler); + public void Subscribe(Func handler) + => _core.Subscribe(handler, WeakEventHandler.Create); /// /// Unsubscribes the specified handler from the event. /// /// The handler to unsubscribe. /// Thrown when is null. - public bool Unsubscribe(Action handler) => base.Unsubscribe(handler); + public bool Unsubscribe(Action handler) => _core.Unsubscribe(handler); /// /// Unsubscribes the specified async handler from the event. /// /// The handler to unsubscribe. /// Thrown when is null. - public bool Unsubscribe(Func handler) => base.Unsubscribe(handler); + public bool Unsubscribe(Func handler) => _core.Unsubscribe(handler); /// /// Unsubscribes the specified async handler from the event. /// /// The handler to unsubscribe. /// Thrown when is null. - public bool Unsubscribe(Func handler) => base.Unsubscribe(handler); + public bool Unsubscribe(Func handler) => _core.Unsubscribe(handler); /// /// Raises the event, invoking all live subscribers with the provided event data. @@ -70,7 +78,7 @@ public class WeakEvent : WeakEventBase /// The event data to publish to the subscribers. /// The cancellation token to cancel the operation. public Task PublishAsync(TEvent eventData, CancellationToken cancellationToken = default) - => base.PublishAsync(eventData, cancellationToken); + => _core.PublishAsync(eventData, cancellationToken); } /// @@ -81,8 +89,15 @@ public Task PublishAsync(TEvent eventData, CancellationToken cancellationToken = /// Weakly referenced event subscribers. Keep your .NET events lean and memory-safe. /// For more information, visit the GitHub repository. /// -public class WeakEvent : WeakEventBase +public class WeakEvent { + private readonly WeakEventCore _core = new(); + + /// + /// Number of living subscribers currently registered to the event. + /// + public int SubscriberCount => _core.SubscriberCount; + /// /// Subscribes the specified handler to the event. /// @@ -91,7 +106,7 @@ public class WeakEvent : WeakEventBase /// provided that the target is still alive. /// /// Thrown when is null. - public void Subscribe(Action handler) => base.SubscribeCore(handler); + public void Subscribe(Action handler) => _core.Subscribe(handler, WeakEventHandler.Create); /// /// Subscribes the specified async handler to the event. @@ -101,7 +116,7 @@ public class WeakEvent : WeakEventBase /// provided that the target is still alive. /// /// Thrown when is null. - public void Subscribe(Func handler) => base.SubscribeCore(handler); + public void Subscribe(Func handler) => _core.Subscribe(handler, WeakEventHandler.Create); /// /// Subscribes the specified async handler with a cancellation token to the event. @@ -111,28 +126,29 @@ public class WeakEvent : WeakEventBase /// provided that the target is still alive. /// /// Thrown when is null. - public void Subscribe(Func handler) => base.SubscribeCore(handler); + public void Subscribe(Func handler) + => _core.Subscribe(handler, WeakEventHandler.Create); /// /// Unsubscribes the specified handler from the event. /// /// The handler to unsubscribe. /// Thrown when is null. - public bool Unsubscribe(Action handler) => base.Unsubscribe(handler); + public bool Unsubscribe(Action handler) => _core.Unsubscribe(handler); /// /// Unsubscribes the specified async handler from the event. /// /// The handler to unsubscribe. /// Thrown when is null. - public bool Unsubscribe(Func handler) => base.Unsubscribe(handler); + public bool Unsubscribe(Func handler) => _core.Unsubscribe(handler); /// /// Unsubscribes the specified async handler from the event. /// /// The handler to unsubscribe. /// Thrown when is null. - public bool Unsubscribe(Func handler) => base.Unsubscribe(handler); + public bool Unsubscribe(Func handler) => _core.Unsubscribe(handler); /// /// Raises the event, invoking all live subscribers with the provided event data. @@ -141,177 +157,5 @@ public class WeakEvent : WeakEventBase /// /// The cancellation token to cancel the operation. public Task PublishAsync(CancellationToken cancellationToken = default) - => base.PublishAsync(null, cancellationToken); -} - -/// -/// Represents a weak event that stores its subscribers using weak references. -/// Subscribers register a and when an event is raised, only those whose target is still alive will be invoked. -/// -public abstract class WeakEventBase -{ - private readonly List _handlers = []; - private readonly ReaderWriterLockSlim _rwLock = new(); - - /// - /// Number of living subscribers currently registered to the event. - /// - public int SubscriberCount - { - get - { - _rwLock.EnterReadLock(); - try - { - return _handlers.Count(x => x.IsAlive); - } - finally - { - _rwLock.ExitReadLock(); - } - } - } - - /// - /// Subscribes the specified delegate handler to the event. - /// - /// - /// The handler to subscribe. It will be invoked when the event is raised, - /// provided that the target is still alive. - /// - /// Thrown when is null. - protected void SubscribeCore(Action handler) - => AddHandlers(handler, WeakEventHandler.Create); - - /// - /// Subscribes the specified delegate handler to the event. - /// - protected void SubscribeCore(Action handler) - => AddHandlers(handler, WeakEventHandler.Create); - - /// - /// Subscribes the specified delegate handler to the event. - /// - protected void SubscribeCore(Func handler) - => AddHandlers(handler, WeakEventHandler.Create); - - /// - /// Subscribes the specified delegate handler to the event. - /// - protected void SubscribeCore(Func handler) - => AddHandlers(handler, WeakEventHandler.Create); - - /// - /// Subscribes the specified delegate handler to the event. - /// - protected void SubscribeCore(Func handler) - => AddHandlers(handler, WeakEventHandler.Create); - - /// - /// Subscribes the specified delegate handler to the event. - /// - protected void SubscribeCore(Func handler) - => AddHandlers(handler, WeakEventHandler.Create); - - private void AddHandlers( - TDelegate handler, - Func createHandler - ) - where TDelegate : Delegate - { - if (handler is null) - { - throw new ArgumentNullException(nameof(handler)); - } - - var handlers = handler - .GetInvocationList() - .Select(invocation => createHandler((TDelegate)invocation)) - .ToArray(); - - _rwLock.EnterWriteLock(); - try - { - _handlers.AddRange(handlers); - } - finally - { - _rwLock.ExitWriteLock(); - } - } - - /// - /// Unsubscribes the specified delegate handler from the event. - /// - /// The handler to unsubscribe. - /// Thrown when is null. - protected bool Unsubscribe(Delegate handler) - { - if (handler is null) - { - throw new ArgumentNullException(nameof(handler)); - } - - var handlers = handler.GetInvocationList(); - - _rwLock.EnterWriteLock(); - try - { - return _handlers.RemoveAll( - weakHandler => handlers.Any(weakHandler.Matches) - ) > 0; - } - finally - { - _rwLock.ExitWriteLock(); - } - } - - /// - /// Raises the event, invoking all live subscribers with the provided event data. - /// Dead subscribers (whose targets have been garbage-collected) are removed. - /// Subscribers are invoked sequentially from a snapshot captured when publication starts. - /// Cancellation is observed before each subscriber is invoked. - /// - /// Event data passed to each data-taking delegate. - /// The cancellation token to cancel the operation. - protected async Task PublishAsync( - object? eventData, - CancellationToken cancellationToken = default - ) - { - List handlers; - - _rwLock.EnterUpgradeableReadLock(); - - try - { - cancellationToken.ThrowIfCancellationRequested(); - - if (_handlers.Any(x => !x.IsAlive)) - { - _rwLock.EnterWriteLock(); - try - { - _handlers.RemoveAll(x => !x.IsAlive); - } - finally - { - _rwLock.ExitWriteLock(); - } - } - - handlers = [.. _handlers]; - } - finally - { - _rwLock.ExitUpgradeableReadLock(); - } - - foreach (var handler in handlers) - { - cancellationToken.ThrowIfCancellationRequested(); - await handler.InvokeAsync(eventData, cancellationToken); - } - } + => _core.PublishAsync(null, cancellationToken); } \ No newline at end of file diff --git a/src/WeakEvent/WeakEventCore.cs b/src/WeakEvent/WeakEventCore.cs new file mode 100644 index 0000000..dba104d --- /dev/null +++ b/src/WeakEvent/WeakEventCore.cs @@ -0,0 +1,112 @@ +namespace ByteAether.WeakEvent; + +internal sealed class WeakEventCore +{ + private readonly List _handlers = []; + private readonly ReaderWriterLockSlim _rwLock = new(); + + public int SubscriberCount + { + get + { + _rwLock.EnterReadLock(); + try + { + return _handlers.Count(x => x.IsAlive); + } + finally + { + _rwLock.ExitReadLock(); + } + } + } + + public void Subscribe( + TDelegate handler, + Func createHandler + ) + where TDelegate : Delegate + { + if (handler is null) + { + throw new ArgumentNullException(nameof(handler)); + } + + var handlers = handler + .GetInvocationList() + .Select(invocation => createHandler((TDelegate)invocation)) + .ToArray(); + + _rwLock.EnterWriteLock(); + try + { + _handlers.AddRange(handlers); + } + finally + { + _rwLock.ExitWriteLock(); + } + } + + public bool Unsubscribe(Delegate handler) + { + if (handler is null) + { + throw new ArgumentNullException(nameof(handler)); + } + + var handlers = handler.GetInvocationList(); + + _rwLock.EnterWriteLock(); + try + { + return _handlers.RemoveAll( + weakHandler => handlers.Any(weakHandler.Matches) + ) > 0; + } + finally + { + _rwLock.ExitWriteLock(); + } + } + + public async Task PublishAsync( + TEvent eventData, + CancellationToken cancellationToken = default + ) + { + List handlers; + + _rwLock.EnterUpgradeableReadLock(); + + try + { + cancellationToken.ThrowIfCancellationRequested(); + + if (_handlers.Any(x => !x.IsAlive)) + { + _rwLock.EnterWriteLock(); + try + { + _handlers.RemoveAll(x => !x.IsAlive); + } + finally + { + _rwLock.ExitWriteLock(); + } + } + + handlers = [.. _handlers]; + } + finally + { + _rwLock.ExitUpgradeableReadLock(); + } + + foreach (var handler in handlers) + { + cancellationToken.ThrowIfCancellationRequested(); + await handler.InvokeAsync(eventData, cancellationToken); + } + } +} \ No newline at end of file diff --git a/src/WeakEvent/WeakEventHandler.cs b/src/WeakEvent/WeakEventHandler.cs index c78c2fe..61a27d6 100644 --- a/src/WeakEvent/WeakEventHandler.cs +++ b/src/WeakEvent/WeakEventHandler.cs @@ -4,7 +4,7 @@ namespace ByteAether.WeakEvent; internal readonly struct WeakEventHandler { - private readonly Func _invoke; + private readonly Delegate _invoke; private readonly MethodInfo _method; // If _weakTarget is null, the handler is static. @@ -12,7 +12,7 @@ internal readonly struct WeakEventHandler private WeakEventHandler( Delegate handler, - Func invoke) + Delegate invoke) { _weakTarget = handler.Target != null ? new WeakReference(handler.Target) : null; _method = handler.Method; @@ -23,7 +23,7 @@ private WeakEventHandler( public bool IsAlive => _weakTarget == null || _weakTarget.Target != null; public static WeakEventHandler Create(Action handler) - => Create( + => Create( handler, (invoke, _, _) => { @@ -33,7 +33,7 @@ public static WeakEventHandler Create(Action handler) ); public static WeakEventHandler Create(Action handler) - => Create( + => Create, TEvent>( handler, (invoke, eventData, _) => { @@ -43,49 +43,58 @@ public static WeakEventHandler Create(Action handler) ); public static WeakEventHandler Create(Func handler) - => Create( + => Create, object?>( handler, (invoke, _, _) => RequireTask(invoke()) ); public static WeakEventHandler Create(Func handler) - => Create( + => Create, TEvent>( handler, (invoke, eventData, _) => RequireTask(invoke((TEvent)eventData!)) ); public static WeakEventHandler Create(Func handler) - => Create( + => Create, object?>( handler, (invoke, _, cancellationToken) => RequireTask(invoke(cancellationToken)) ); public static WeakEventHandler Create(Func handler) - => Create( + => Create, TEvent>( handler, (invoke, eventData, cancellationToken) => RequireTask(invoke((TEvent)eventData!, cancellationToken)) ); public Task InvokeAsync(object? eventData, CancellationToken cancellationToken = default) + => InvokeAsync(eventData, cancellationToken); + + public Task InvokeAsync( + TEvent eventData, + CancellationToken cancellationToken = default + ) { - // Get target first so it would not be GCed before the method is invoked. - var target = _weakTarget?.Target; + var target = GetTarget(); - if (_weakTarget != null && target == null) + if (target == null && _weakTarget != null) { return Task.CompletedTask; } - return _invoke(target, eventData, cancellationToken); + return ((Func)_invoke)( + target, + eventData, + cancellationToken + ); } public bool Matches(Delegate handler) => ReferenceEquals(_weakTarget?.Target, handler.Target) && _method.Equals(handler.Method); - private static WeakEventHandler Create( + private static WeakEventHandler Create( TDelegate handler, - Func invoke + Func invoke ) where TDelegate : Delegate { @@ -100,24 +109,35 @@ private static WeakEventHandler Create( var method = handler.Method; - return new WeakEventHandler( + return CreateHandler( handler, - (target, eventData, cancellationToken) => - invoke(GetDelegate(method, target), eventData, cancellationToken) + (Func)( + (target, eventData, cancellationToken) => + invoke(GetDelegate(method, target), eventData, cancellationToken) + ) ); } - private static WeakEventHandler CreateTargetless( + private static WeakEventHandler CreateTargetless( TDelegate handler, - Func invoke + Func invoke ) where TDelegate : Delegate - => new( + => CreateHandler( handler, - (_, eventData, cancellationToken) => - invoke(handler, eventData, cancellationToken) + (Func)( + (_, eventData, cancellationToken) => + invoke(handler, eventData, cancellationToken) + ) ); + private static WeakEventHandler CreateHandler( + Delegate handler, + Func invoke + ) => new(handler, invoke); + + private object? GetTarget() => _weakTarget?.Target; + private static TDelegate GetDelegate(MethodInfo method, object? target) where TDelegate : Delegate => (TDelegate)Delegate.CreateDelegate(typeof(TDelegate), target!, method); @@ -132,4 +152,4 @@ private static void ThrowIfNull(Delegate? handler) throw new ArgumentNullException(nameof(handler)); } } -} \ No newline at end of file +} \ No newline at end of file