Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions src/WeakEvent.Tests/WeakEventGenericTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>();
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<string>();
using var cancellationTokenSource = new CancellationTokenSource();
var secondHandlerCalled = false;

weakEvent.Subscribe((string _) => cancellationTokenSource.Cancel());
weakEvent.Subscribe((string _) => secondHandlerCalled = true);

await Assert.ThrowsAnyAsync<OperationCanceledException>(
() => weakEvent.PublishAsync("Test event", cancellationTokenSource.Token)
);
Assert.False(secondHandlerCalled);
}

[Fact]
public async Task PublishAsync_SynchronousHandlerException_IsNotWrapped()
{
var weakEvent = new WeakEvent<string>();
weakEvent.Subscribe((Action<string>)(_ => throw new TestException()));

await Assert.ThrowsAsync<TestException>(() => weakEvent.PublishAsync("Test event"));
}

[Fact]
public async Task PublishAsync_AsyncHandlerReturningNull_ThrowsInvalidOperationException()
{
var weakEvent = new WeakEvent<string>();
weakEvent.Subscribe((Func<string, Task>)(_ => null!));

await Assert.ThrowsAsync<InvalidOperationException>(() => weakEvent.PublishAsync("Test event"));
}

[Fact]
public async Task DeadHandler_IsNotInvoked_AfterGarbageCollection()
{
Expand Down Expand Up @@ -179,4 +235,6 @@ private class GenericSubscriber(Action onEvent)

public void Handler(string _) => _onEvent();
}

private sealed class TestException : Exception;
}
24 changes: 12 additions & 12 deletions src/WeakEvent.Tests/WeakEventHandlerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,24 @@
public class WeakEventHandlerTests
{
[Fact]
public void Constructor_NullDelegate_ThrowsException()
public void Create_NullDelegate_ThrowsException()
{
// Arrange
Action handler = null!;

// Act & Assert
Assert.Throws<NullReferenceException>(() => new WeakEventHandler(handler));
Assert.Throws<ArgumentNullException>(() => WeakEventHandler.Create(handler));
}

[Fact]
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);
Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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.
}

Expand Down
78 changes: 62 additions & 16 deletions src/WeakEvent/WeakEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class WeakEvent<TEvent> : WeakEventBase
/// provided that the target is still alive.
/// </param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="handler"/> is null.</exception>
public void Subscribe(Action<TEvent> handler) => base.Subscribe(handler);
public void Subscribe(Action<TEvent> handler) => base.SubscribeCore(handler);

/// <summary>
/// Subscribes the specified async handler to the event.
Expand All @@ -29,7 +29,7 @@ public class WeakEvent<TEvent> : WeakEventBase
/// provided that the target is still alive.
/// </param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="handler"/> is null.</exception>
public void Subscribe(Func<TEvent, Task> handler) => base.Subscribe(handler);
public void Subscribe(Func<TEvent, Task> handler) => base.SubscribeCore(handler);

/// <summary>
/// Subscribes the specified async handler with a cancellation token to the event.
Expand All @@ -39,7 +39,7 @@ public class WeakEvent<TEvent> : WeakEventBase
/// provided that the target is still alive.
/// </param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="handler"/> is null.</exception>
public void Subscribe(Func<TEvent, CancellationToken, Task> handler) => base.Subscribe(handler);
public void Subscribe(Func<TEvent, CancellationToken, Task> handler) => base.SubscribeCore(handler);

/// <summary>
/// Unsubscribes the specified handler from the event.
Expand All @@ -65,11 +65,12 @@ public class WeakEvent<TEvent> : WeakEventBase
/// <summary>
/// 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.
/// </summary>
/// <param name="eventData">The event data to publish to the subscribers.</param>
/// <param name="cancellationToken">The cancellation token to cancel the operation.</param>
public Task PublishAsync(TEvent eventData, CancellationToken cancellationToken = default)
=> base.PublishAsync([eventData], cancellationToken);
=> base.PublishAsync(eventData, cancellationToken);
}

/// <summary>
Expand All @@ -90,7 +91,7 @@ public class WeakEvent : WeakEventBase
/// provided that the target is still alive.
/// </param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="handler"/> is null.</exception>
public void Subscribe(Action handler) => base.Subscribe(handler);
public void Subscribe(Action handler) => base.SubscribeCore(handler);

/// <summary>
/// Subscribes the specified async handler to the event.
Expand All @@ -100,7 +101,7 @@ public class WeakEvent : WeakEventBase
/// provided that the target is still alive.
/// </param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="handler"/> is null.</exception>
public void Subscribe(Func<Task> handler) => base.Subscribe(handler);
public void Subscribe(Func<Task> handler) => base.SubscribeCore(handler);

/// <summary>
/// Subscribes the specified async handler with a cancellation token to the event.
Expand All @@ -110,7 +111,7 @@ public class WeakEvent : WeakEventBase
/// provided that the target is still alive.
/// </param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="handler"/> is null.</exception>
public void Subscribe(Func<CancellationToken, Task> handler) => base.Subscribe(handler);
public void Subscribe(Func<CancellationToken, Task> handler) => base.SubscribeCore(handler);

/// <summary>
/// Unsubscribes the specified handler from the event.
Expand All @@ -136,9 +137,11 @@ public class WeakEvent : WeakEventBase
/// <summary>
/// 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.
/// </summary>
/// <param name="cancellationToken">The cancellation token to cancel the operation.</param>
public Task PublishAsync(CancellationToken cancellationToken = default) => base.PublishAsync([], cancellationToken);
public Task PublishAsync(CancellationToken cancellationToken = default)
=> base.PublishAsync(null, cancellationToken);
}

/// <summary>
Expand Down Expand Up @@ -177,17 +180,56 @@ public int SubscriberCount
/// provided that the target is still alive.
/// </param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="handler"/> is null.</exception>
protected void Subscribe(Delegate handler)
protected void SubscribeCore(Action handler)
=> AddHandlers(handler, WeakEventHandler.Create);

/// <summary>
/// Subscribes the specified delegate handler to the event.
/// </summary>
protected void SubscribeCore<TEvent>(Action<TEvent> handler)
=> AddHandlers(handler, WeakEventHandler.Create);

/// <summary>
/// Subscribes the specified delegate handler to the event.
/// </summary>
protected void SubscribeCore(Func<Task> handler)
=> AddHandlers(handler, WeakEventHandler.Create);

/// <summary>
/// Subscribes the specified delegate handler to the event.
/// </summary>
protected void SubscribeCore<TEvent>(Func<TEvent, Task> handler)
=> AddHandlers(handler, WeakEventHandler.Create);

/// <summary>
/// Subscribes the specified delegate handler to the event.
/// </summary>
protected void SubscribeCore(Func<CancellationToken, Task> handler)
=> AddHandlers(handler, WeakEventHandler.Create);

/// <summary>
/// Subscribes the specified delegate handler to the event.
/// </summary>
protected void SubscribeCore<TEvent>(Func<TEvent, CancellationToken, Task> handler)
=> AddHandlers(handler, WeakEventHandler.Create);

private void AddHandlers<TDelegate>(
TDelegate handler,
Func<TDelegate, WeakEventHandler> 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
{
Expand All @@ -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
{
Expand All @@ -221,10 +263,15 @@ protected bool Unsubscribe(Delegate handler)
/// <summary>
/// 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.
/// </summary>
/// <param name="args">Invocation arguments for each delegate</param>
/// <param name="eventData">Event data passed to each data-taking delegate.</param>
/// <param name="cancellationToken">The cancellation token to cancel the operation.</param>
protected async Task PublishAsync(List<object?> args, CancellationToken cancellationToken = default)
protected async Task PublishAsync(
object? eventData,
CancellationToken cancellationToken = default
)
{
List<WeakEventHandler> handlers;

Expand Down Expand Up @@ -254,11 +301,10 @@ protected async Task PublishAsync(List<object?> args, CancellationToken cancella
_rwLock.ExitUpgradeableReadLock();
}

cancellationToken.ThrowIfCancellationRequested();

foreach (var handler in handlers)
{
await handler.InvokeAsync(args, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
await handler.InvokeAsync(eventData, cancellationToken);
}
}
}
Loading