From 85b54b3be2edb6945964993da0a2dfb16ec91a11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joonatan=20Uusv=C3=A4li?= Date: Sun, 22 Nov 2026 17:35:50 +0200 Subject: [PATCH] Make weak event dispatch type-safe and deterministic --- src/WeakEvent.Tests/WeakEventGenericTests.cs | 58 ++++++++++ src/WeakEvent.Tests/WeakEventHandlerTests.cs | 24 ++-- src/WeakEvent/WeakEvent.cs | 78 ++++++++++--- src/WeakEvent/WeakEventHandler.cs | 109 +++++++++++++++++-- 4 files changed, 229 insertions(+), 40 deletions(-) diff --git a/src/WeakEvent.Tests/WeakEventGenericTests.cs b/src/WeakEvent.Tests/WeakEventGenericTests.cs index 35f6a0a..cfefb7b 100644 --- a/src/WeakEvent.Tests/WeakEventGenericTests.cs +++ b/src/WeakEvent.Tests/WeakEventGenericTests.cs @@ -113,6 +113,62 @@ async Task asyncHandlerCt(int x, CancellationToken ct) Assert.Equal(14, count); } + [Fact] + public async Task CancellationTokenHandler_DoesNotAlterArgumentsForFollowingHandler() + { + var weakEvent = new WeakEvent(); + var tokenHandlerCalled = false; + var syncHandlerCalled = false; + + weakEvent.Subscribe( + (string _, CancellationToken _) => + { + tokenHandlerCalled = true; + return Task.CompletedTask; + } + ); + weakEvent.Subscribe((string _) => syncHandlerCalled = true); + + await weakEvent.PublishAsync("Test event"); + + Assert.True(tokenHandlerCalled); + Assert.True(syncHandlerCalled); + } + + [Fact] + public async Task PublishAsync_CancellationBetweenHandlers_StopsDispatch() + { + var weakEvent = new WeakEvent(); + using var cancellationTokenSource = new CancellationTokenSource(); + var secondHandlerCalled = false; + + weakEvent.Subscribe((string _) => cancellationTokenSource.Cancel()); + weakEvent.Subscribe((string _) => secondHandlerCalled = true); + + await Assert.ThrowsAnyAsync( + () => weakEvent.PublishAsync("Test event", cancellationTokenSource.Token) + ); + Assert.False(secondHandlerCalled); + } + + [Fact] + public async Task PublishAsync_SynchronousHandlerException_IsNotWrapped() + { + var weakEvent = new WeakEvent(); + weakEvent.Subscribe((Action)(_ => throw new TestException())); + + await Assert.ThrowsAsync(() => weakEvent.PublishAsync("Test event")); + } + + [Fact] + public async Task PublishAsync_AsyncHandlerReturningNull_ThrowsInvalidOperationException() + { + var weakEvent = new WeakEvent(); + weakEvent.Subscribe((Func)(_ => null!)); + + await Assert.ThrowsAsync(() => weakEvent.PublishAsync("Test event")); + } + [Fact] public async Task DeadHandler_IsNotInvoked_AfterGarbageCollection() { @@ -179,4 +235,6 @@ private class GenericSubscriber(Action onEvent) public void Handler(string _) => _onEvent(); } + + private sealed class TestException : Exception; } \ No newline at end of file diff --git a/src/WeakEvent.Tests/WeakEventHandlerTests.cs b/src/WeakEvent.Tests/WeakEventHandlerTests.cs index 5534fba..84ca7c7 100644 --- a/src/WeakEvent.Tests/WeakEventHandlerTests.cs +++ b/src/WeakEvent.Tests/WeakEventHandlerTests.cs @@ -3,13 +3,13 @@ public class WeakEventHandlerTests { [Fact] - public void Constructor_NullDelegate_ThrowsException() + public void Create_NullDelegate_ThrowsException() { // Arrange Action handler = null!; // Act & Assert - Assert.Throws(() => new WeakEventHandler(handler)); + Assert.Throws(() => WeakEventHandler.Create(handler)); } [Fact] @@ -17,10 +17,10 @@ public async Task StaticHandler_InvokeAsync_Void() { // Arrange _staticInvoked = false; - var weakHandler = new WeakEventHandler(StaticHandler); + var weakHandler = WeakEventHandler.Create(StaticHandler); // Act - await weakHandler.InvokeAsync([]); + await weakHandler.InvokeAsync(null); // Assert Assert.True(_staticInvoked); @@ -35,10 +35,10 @@ public async Task InstanceHandler_InvokeAsync_Void() { // Arrange var subscriber = new Subscriber(); - var weakHandler = new WeakEventHandler(subscriber.InstanceHandler); + var weakHandler = WeakEventHandler.Create(subscriber.InstanceHandler); // Act - await weakHandler.InvokeAsync([]); + await weakHandler.InvokeAsync(null); // Assert Assert.True(subscriber.Invoked); @@ -50,10 +50,10 @@ public async Task InstanceHandler_InvokeAsync_Async() { // Arrange var subscriber = new Subscriber(); - var weakHandler = new WeakEventHandler(subscriber.AsyncHandler); + var weakHandler = WeakEventHandler.Create(subscriber.AsyncHandler); // Act - await weakHandler.InvokeAsync([]); + await weakHandler.InvokeAsync(null); // Assert Assert.True(subscriber.Invoked); @@ -65,7 +65,7 @@ public void Matches_ReturnsTrueForSameDelegate() { // Arrange var subscriber = new Subscriber(); - var weakHandler = new WeakEventHandler(subscriber.InstanceHandler); + var weakHandler = WeakEventHandler.Create(subscriber.InstanceHandler); // Act var result = weakHandler.Matches(subscriber.InstanceHandler); @@ -80,7 +80,7 @@ public void Matches_ReturnsFalseForDifferentDelegate() // Arrange var subscriber1 = new Subscriber(); var subscriber2 = new Subscriber(); - var weakHandler = new WeakEventHandler(subscriber1.InstanceHandler); + var weakHandler = WeakEventHandler.Create(subscriber1.InstanceHandler); // Act var result = weakHandler.Matches(subscriber2.InstanceHandler); @@ -100,7 +100,7 @@ public async Task InvokeAsync_ForDeadInstance_DoesNotInvoke() GC.WaitForPendingFinalizers(); var isAliveBefore = weakHandler.IsAlive; - await weakHandler.InvokeAsync([]); + await weakHandler.InvokeAsync(null); // Assert Assert.False(isAliveBefore); @@ -112,7 +112,7 @@ private static WeakEventHandler CreateWeakSubscriber() { ThrowIfInvoked = true }; - return new WeakEventHandler(subscriber.InstanceHandler); + return WeakEventHandler.Create(subscriber.InstanceHandler); // 'subscriber' goes out of scope after this method. } diff --git a/src/WeakEvent/WeakEvent.cs b/src/WeakEvent/WeakEvent.cs index 6144640..a0c7790 100644 --- a/src/WeakEvent/WeakEvent.cs +++ b/src/WeakEvent/WeakEvent.cs @@ -19,7 +19,7 @@ public class WeakEvent : WeakEventBase /// provided that the target is still alive. /// /// Thrown when is null. - public void Subscribe(Action handler) => base.Subscribe(handler); + public void Subscribe(Action handler) => base.SubscribeCore(handler); /// /// Subscribes the specified async handler to the event. @@ -29,7 +29,7 @@ public class WeakEvent : WeakEventBase /// provided that the target is still alive. /// /// Thrown when is null. - public void Subscribe(Func handler) => base.Subscribe(handler); + public void Subscribe(Func handler) => base.SubscribeCore(handler); /// /// Subscribes the specified async handler with a cancellation token to the event. @@ -39,7 +39,7 @@ public class WeakEvent : WeakEventBase /// provided that the target is still alive. /// /// Thrown when is null. - public void Subscribe(Func handler) => base.Subscribe(handler); + public void Subscribe(Func handler) => base.SubscribeCore(handler); /// /// Unsubscribes the specified handler from the event. @@ -65,11 +65,12 @@ public class WeakEvent : WeakEventBase /// /// 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. /// /// 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); + => base.PublishAsync(eventData, cancellationToken); } /// @@ -90,7 +91,7 @@ public class WeakEvent : WeakEventBase /// provided that the target is still alive. /// /// Thrown when is null. - public void Subscribe(Action handler) => base.Subscribe(handler); + public void Subscribe(Action handler) => base.SubscribeCore(handler); /// /// Subscribes the specified async handler to the event. @@ -100,7 +101,7 @@ public class WeakEvent : WeakEventBase /// provided that the target is still alive. /// /// Thrown when is null. - public void Subscribe(Func handler) => base.Subscribe(handler); + public void Subscribe(Func handler) => base.SubscribeCore(handler); /// /// Subscribes the specified async handler with a cancellation token to the event. @@ -110,7 +111,7 @@ public class WeakEvent : WeakEventBase /// provided that the target is still alive. /// /// Thrown when is null. - public void Subscribe(Func handler) => base.Subscribe(handler); + public void Subscribe(Func handler) => base.SubscribeCore(handler); /// /// Unsubscribes the specified handler from the event. @@ -136,9 +137,11 @@ public class WeakEvent : WeakEventBase /// /// 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. /// /// The cancellation token to cancel the operation. - public Task PublishAsync(CancellationToken cancellationToken = default) => base.PublishAsync([], cancellationToken); + public Task PublishAsync(CancellationToken cancellationToken = default) + => base.PublishAsync(null, cancellationToken); } /// @@ -177,17 +180,56 @@ public int SubscriberCount /// provided that the target is still alive. /// /// Thrown when is null. - protected void Subscribe(Delegate handler) + 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 weakHandler = createHandler(handler); + _rwLock.EnterWriteLock(); try { - _handlers.Add(new WeakEventHandler(handler)); + _handlers.Add(weakHandler); } finally { @@ -210,7 +252,7 @@ protected bool Unsubscribe(Delegate handler) _rwLock.EnterWriteLock(); try { - return _handlers.RemoveAll(weh => weh.Matches(handler)) > 0; + return _handlers.RemoveAll(weakHandler => weakHandler.Matches(handler)) > 0; } finally { @@ -221,10 +263,15 @@ protected bool Unsubscribe(Delegate handler) /// /// 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. /// - /// Invocation arguments for each delegate + /// Event data passed to each data-taking delegate. /// The cancellation token to cancel the operation. - protected async Task PublishAsync(List args, CancellationToken cancellationToken = default) + protected async Task PublishAsync( + object? eventData, + CancellationToken cancellationToken = default + ) { List handlers; @@ -254,11 +301,10 @@ protected async Task PublishAsync(List args, CancellationToken cancella _rwLock.ExitUpgradeableReadLock(); } - cancellationToken.ThrowIfCancellationRequested(); - foreach (var handler in handlers) { - await handler.InvokeAsync(args, cancellationToken); + 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 14da844..11c1102 100644 --- a/src/WeakEvent/WeakEventHandler.cs +++ b/src/WeakEvent/WeakEventHandler.cs @@ -2,34 +2,119 @@ namespace ByteAether.WeakEvent; -internal readonly struct WeakEventHandler(Delegate handler) +internal readonly struct WeakEventHandler { + private readonly Func _invoke; + private readonly MethodInfo _method; + // If _weakTarget is null, the handler is static. - private readonly WeakReference? _weakTarget = handler.Target != null ? new WeakReference(handler.Target) : null; - private readonly MethodInfo _method = handler.Method; - private readonly bool _hasCtParam = handler.Method.GetParameters().LastOrDefault()?.ParameterType == typeof(CancellationToken); + private readonly WeakReference? _weakTarget; + + private WeakEventHandler( + Delegate handler, + Func invoke) + { + _weakTarget = handler.Target != null ? new WeakReference(handler.Target) : null; + _method = handler.Method; + _invoke = invoke; + } // If _weakTarget is null, the handler is static and always alive. public bool IsAlive => _weakTarget == null || _weakTarget.Target != null; - public Task InvokeAsync(List args, CancellationToken cancellationToken = default) + public static WeakEventHandler Create(Action handler) + => Create( + handler, + (invoke, _, _) => + { + invoke(); + return Task.CompletedTask; + } + ); + + public static WeakEventHandler Create(Action handler) + => Create( + handler, + (invoke, eventData, _) => + { + invoke((TEvent)eventData!); + return Task.CompletedTask; + } + ); + + public static WeakEventHandler Create(Func handler) + => Create( + handler, + (invoke, _, _) => RequireTask(invoke()) + ); + + public static WeakEventHandler Create(Func handler) + => Create( + handler, + (invoke, eventData, _) => RequireTask(invoke((TEvent)eventData!)) + ); + + public static WeakEventHandler Create(Func handler) + => Create( + handler, + (invoke, _, cancellationToken) => RequireTask(invoke(cancellationToken)) + ); + + public static WeakEventHandler Create(Func handler) + => Create( + handler, + (invoke, eventData, cancellationToken) => + RequireTask(invoke((TEvent)eventData!, cancellationToken)) + ); + + public Task InvokeAsync(object? eventData, CancellationToken cancellationToken = default) { // Get target first so it would not be GCed before the method is invoked. var target = _weakTarget?.Target; - if (!IsAlive) + if (_weakTarget != null && target == null) { return Task.CompletedTask; } - if (_hasCtParam) - { - args.Add(cancellationToken); - } - - return _method.Invoke(target, [.. args]) as Task ?? Task.CompletedTask; + return _invoke(target, eventData, cancellationToken); } public bool Matches(Delegate handler) => _weakTarget?.Target == handler.Target && _method.Equals(handler.Method); + + private static WeakEventHandler Create( + TDelegate handler, + Func invoke + ) + where TDelegate : Delegate + { + ThrowIfNull(handler); + var method = handler.Method; + + return new WeakEventHandler( + handler, + (target, eventData, cancellationToken) => + invoke(GetDelegate(method, target), eventData, cancellationToken) + ); + } + + private static TDelegate GetDelegate(MethodInfo method, object? target) + where TDelegate : Delegate + => (TDelegate)( + target == null + ? Delegate.CreateDelegate(typeof(TDelegate), method) + : Delegate.CreateDelegate(typeof(TDelegate), target, method) + ); + + private static Task RequireTask(Task? task) + => task ?? throw new InvalidOperationException("An asynchronous event handler returned a null Task."); + + private static void ThrowIfNull(Delegate? handler) + { + if (handler == null) + { + throw new ArgumentNullException(nameof(handler)); + } + } } \ No newline at end of file