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
2 changes: 1 addition & 1 deletion .github/workflows/build-and-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ jobs:
run: dotnet build --no-restore --configuration Release src/WeakEvent.sln

- name: Run tests
continue-on-error: true
run: dotnet test --no-build --verbosity normal --logger "trx" --configuration Release src/WeakEvent.sln

- name: Upload test results
if: always()
uses: actions/upload-artifact@v7
with:
name: test-results
Expand Down
78 changes: 57 additions & 21 deletions src/WeakEvent.Tests/WeakEventGenericTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;

namespace ByteAether.WeakEvent.Tests;

Expand Down Expand Up @@ -196,19 +197,10 @@ public async Task DeadHandler_IsNotInvoked_AfterGarbageCollection()
var weakEvent = new WeakEvent<string>();
var callCount = 0;

static async Task createSubscriberAndInvoke(WeakEvent<string> weakEvent, Action onEvent)
{
var subscriber = new GenericSubscriber(onEvent);
weakEvent.Subscribe(subscriber.Handler);
await weakEvent.PublishAsync("Test");
// The subscriber goes out of scope after this method, allowing it to be GC’d.
}

await createSubscriberAndInvoke(weakEvent, () => callCount++);
await SubscribeAndInvokeAsync(weakEvent, () => callCount++);

// Force garbage collection to reclaim the subscriber instance.
GC.Collect();
GC.WaitForPendingFinalizers();
CollectGarbage();

// Invoke a second time
await weakEvent.PublishAsync("Test");
Expand All @@ -232,25 +224,69 @@ void syncHandler(string _)
weakEvent.Subscribe(syncHandler);

// Stage 3 - Add a garbage-collected handler
void createSubscriberAndAssert()
{
var subscriber = new GenericSubscriber(() => { });
weakEvent.Subscribe(subscriber.Handler);
Assert.Equal(2, weakEvent.SubscriberCount);
}

createSubscriberAndAssert();
SubscribeAndAssert(weakEvent);

// Stage 4 - Force garbage collection to reclaim the garbage-collectable subscriber instance.
GC.Collect();
GC.WaitForPendingFinalizers();
CollectGarbage();
Assert.Equal(1, weakEvent.SubscriberCount);

// Stage 5 - Remove local handler
weakEvent.Unsubscribe(syncHandler);
Assert.Equal(0, weakEvent.SubscriberCount);
}

[Fact]
public async Task OpenInstanceHandler_IsInvoked()
{
var weakEvent = new WeakEvent<OpenInstanceSubscriber>();
var method = typeof(OpenInstanceSubscriber).GetMethod(nameof(OpenInstanceSubscriber.Handler))!;
var handler = (Action<OpenInstanceSubscriber>)Delegate.CreateDelegate(
typeof(Action<OpenInstanceSubscriber>),
method
);
var subscriber = new OpenInstanceSubscriber();

weakEvent.Subscribe(handler);
await weakEvent.PublishAsync(subscriber);

Assert.Equal(1, subscriber.CallCount);
}

private class OpenInstanceSubscriber
{
public int CallCount { get; private set; }

public void Handler() => CallCount++;
}

[MethodImpl(MethodImplOptions.NoInlining)]
private static async Task SubscribeAndInvokeAsync(WeakEvent<string> weakEvent, Action onEvent)
{
var subscriber = new GenericSubscriber(onEvent);
weakEvent.Subscribe(subscriber.Handler);
await weakEvent.PublishAsync("Test");
GC.KeepAlive(subscriber);
}

[MethodImpl(MethodImplOptions.NoInlining)]
private static void SubscribeAndAssert(WeakEvent<string> weakEvent)
{
var subscriber = new GenericSubscriber(() => { });
weakEvent.Subscribe(subscriber.Handler);
Assert.Equal(2, weakEvent.SubscriberCount);
GC.KeepAlive(subscriber);
}

[MethodImpl(MethodImplOptions.NoInlining)]
private static void CollectGarbage()
{
for (var i = 0; i < 3; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}

private class GenericSubscriber(Action onEvent)
{
private readonly Action _onEvent = onEvent;
Expand Down
12 changes: 10 additions & 2 deletions src/WeakEvent.Tests/WeakEventHandlerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,7 @@ public async Task InvokeAsync_ForDeadInstance_DoesNotInvoke()
var weakHandler = CreateWeakSubscriber();

// Act
GC.Collect();
GC.WaitForPendingFinalizers();
CollectGarbage();

var isAliveBefore = weakHandler.IsAlive;
await weakHandler.InvokeAsync(null);
Expand Down Expand Up @@ -142,4 +141,13 @@ public async Task AsyncHandler()
await Task.CompletedTask;
}
}

private static void CollectGarbage()
{
for (var i = 0; i < 3; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
57 changes: 35 additions & 22 deletions src/WeakEvent.Tests/WeakEventNonGenericTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
namespace ByteAether.WeakEvent.Tests;
using System.Runtime.CompilerServices;

namespace ByteAether.WeakEvent.Tests;

public class WeakEventNonGenericTests
{
Expand Down Expand Up @@ -119,19 +121,10 @@ public async Task DeadHandler_IsNotInvoked_AfterGarbageCollection()
var weakEvent = new WeakEvent();
var callCount = 0;

static async Task createSubscriberAndInvoke(WeakEvent weakEvent, Action onEvent)
{
var subscriber = new NonGenericSubscriber(onEvent);
weakEvent.Subscribe(subscriber.Handler);
await weakEvent.PublishAsync();
// The subscriber goes out of scope after this method, allowing it to be GC’d.
}

await createSubscriberAndInvoke(weakEvent, () => callCount++);
await SubscribeAndInvokeAsync(weakEvent, () => callCount++);

// Force garbage collection to reclaim the subscriber instance.
GC.Collect();
GC.WaitForPendingFinalizers();
CollectGarbage();

// Invoke a second time
await weakEvent.PublishAsync();
Expand All @@ -155,25 +148,45 @@ void syncHandler()
Assert.Equal(1, weakEvent.SubscriberCount);

// Stage 3 - Add a garbage-collected handler
void createSubscriberAndAssert()
{
var subscriber = new NonGenericSubscriber(() => { });
weakEvent.Subscribe(subscriber.Handler);
Assert.Equal(2, weakEvent.SubscriberCount);
}

createSubscriberAndAssert();
SubscribeAndAssert(weakEvent);

// Stage 4 - Force garbage collection to reclaim the garbage-collectable subscriber instance.
GC.Collect();
GC.WaitForPendingFinalizers();
CollectGarbage();
Assert.Equal(1, weakEvent.SubscriberCount);

// Stage 5 - Remove local handler
weakEvent.Unsubscribe(syncHandler);
Assert.Equal(0, weakEvent.SubscriberCount);
}

[MethodImpl(MethodImplOptions.NoInlining)]
private static async Task SubscribeAndInvokeAsync(WeakEvent weakEvent, Action onEvent)
{
var subscriber = new NonGenericSubscriber(onEvent);
weakEvent.Subscribe(subscriber.Handler);
await weakEvent.PublishAsync();
GC.KeepAlive(subscriber);
}

[MethodImpl(MethodImplOptions.NoInlining)]
private static void SubscribeAndAssert(WeakEvent weakEvent)
{
var subscriber = new NonGenericSubscriber(() => { });
weakEvent.Subscribe(subscriber.Handler);
Assert.Equal(2, weakEvent.SubscriberCount);
GC.KeepAlive(subscriber);
}

[MethodImpl(MethodImplOptions.NoInlining)]
private static void CollectGarbage()
{
for (var i = 0; i < 3; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}

private class NonGenericSubscriber(Action onEvent)
{
private readonly Action _onEvent = onEvent;
Expand Down
25 changes: 20 additions & 5 deletions src/WeakEvent/WeakEventHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,14 @@ private static WeakEventHandler Create<TDelegate>(
where TDelegate : Delegate
{
ThrowIfNull(handler);

// Delegates for static methods and open-instance methods both have no target.
// Retaining those delegates is safe and avoids reconstructing them as static delegates.
if (handler.Target == null)
{
return CreateTargetless(handler, invoke);
}

var method = handler.Method;

return new WeakEventHandler(
Expand All @@ -99,14 +107,21 @@ private static WeakEventHandler Create<TDelegate>(
);
}

private static TDelegate GetDelegate<TDelegate>(MethodInfo method, object? target)
private static WeakEventHandler CreateTargetless<TDelegate>(
TDelegate handler,
Func<TDelegate, object?, CancellationToken, Task> invoke
)
where TDelegate : Delegate
=> (TDelegate)(
target == null
? Delegate.CreateDelegate(typeof(TDelegate), method)
: Delegate.CreateDelegate(typeof(TDelegate), target, method)
=> new(
handler,
(_, eventData, cancellationToken) =>
invoke(handler, eventData, cancellationToken)
);

private static TDelegate GetDelegate<TDelegate>(MethodInfo method, object? target)
where TDelegate : Delegate
=> (TDelegate)Delegate.CreateDelegate(typeof(TDelegate), target!, method);

private static Task RequireTask(Task? task)
=> task ?? throw new InvalidOperationException("An asynchronous event handler returned a null Task.");

Expand Down