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
125 changes: 77 additions & 48 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# ![WeakEvent from ByteAether](assets/header.png)
# ![WeakEvent from ByteAether](assets/header_weakevent.png)

[![License](https://img.shields.io/github/license/ByteAether/WeakEvent?logo=github&label=License)](https://github.com/ByteAether/WeakEvent/blob/main/LICENSE)
[![NuGet Version](https://img.shields.io/nuget/v/ByteAether.WeakEvent?logo=nuget&label=Version)](https://www.nuget.org/packages/ByteAether.WeakEvent/)
Expand All @@ -10,41 +10,62 @@ Weakly referenced event subscribers. Keep your .NET events lean and memory-safe.

## Introduction

<img align="right" width="100px" src="assets/logo.png" />
<img align="right" width="100px" src="assets/logo_weakevent.png" />

The weak event pattern is a proven approach to managing event subscriptions in .NET, as detailed in Microsoft's documentation on [WPF weak event patterns](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/events/weak-event-patterns?view=netdesktop-9.0). This design avoids memory leaks by holding event subscribers with weak references, which means that even if an object remains subscribed to an event, it can still be garbage collected when no longer in use.
WeakEvent is a .NET implementation of the weak event pattern for applications that publish notifications to objects
whose lifetimes may not be controlled by the publisher. A normal event holds references to its subscribers, so an object
that is no longer in use can remain in memory until it explicitly unsubscribes. This becomes a source of memory leaks or
stale component state when subscriptions outlive their owner.

Leveraging the power of .NET's weak reference mechanism, as explained in the [.NET garbage collection documentation](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/weak-references), the WeakEvent library ensures that event subscribers do not prevent the garbage collector from reclaiming memory. This decoupling of publishers and subscribers provides a robust solution for managing event lifecycles without the need for manual unsubscription.
WeakEvent breaks that reference cycle by retaining instance handlers weakly. When the subscriber object is no longer
used elsewhere, the garbage collector can reclaim it even while a subscription remains registered. Static handlers
remain alive for the lifetime of the event source. No unsubscription is required, although handlers can still be removed
explicitly. Dead subscriptions are ignored and cleaned up during publication.

In the context of Blazor components, this functionality is particularly valuable. When using Blazor, developers often face challenges with unsubscribing from events during component disposal. With WeakEvent, you can safely subscribe to events in your Blazor components without worrying about leftover subscriptions that could block garbage collection. This ensures that unloaded components are properly cleaned up, preventing the accumulation of dead components in memory and avoiding potential memory leaks.
The library supports synchronous and asynchronous handlers, notifications with or without payload data, and
cancellation-aware publishing. It fits event-driven applications where publishers are long-lived and subscribers are
short-lived or repeatedly created, such as UI components, services that observe background processes, desktop
applications, and Blazor components. It is especially useful when component disposal and other lifecycle boundaries make
manual unsubscription difficult or easy to miss.

For background on the pattern, see Microsoft's documentation
on [WPF weak event patterns](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/events/weak-event-patterns?view=netdesktop-9.0)
and [.NET weak references](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/weak-references).

## Features

![.NET Standard 2.0](https://img.shields.io/badge/.NET_Standard-2.0-brightgreen)

- **Weak References:** Subscribers are held via weak references, allowing the garbage collector to reclaim them when they are no longer needed.
- **Events With or Without Data:** Use `WeakEvent<TEvent>` when you need to pass event data to subscribers, or `WeakEvent` for simple notifications that don't require additional information.
- **Automatic Cleanup:** Dead subscribers (whose targets have been garbage-collected) are automatically removed when the event is raised.
- **Simple API:** Intuitive methods for subscribing, unsubscribing, and publishing events.
- **Weak References:** Subscribers are held weakly so they can be garbage-collected when no longer in use.
- **Events With or Without Payloads:** Use `WeakEvent` for notifications or `WeakEvent<TEvent>` to pass event data.
- **Synchronous and Asynchronous Handlers:** Subscribe with `Action`, `Func<Task>`, or a cancellation-aware async
delegate.
- **Automatic Cleanup:** Dead subscribers are removed during publication.
- **Simple API:** Methods for subscribing, unsubscribing, and publishing.

### Publication behavior

- Subscribers are invoked sequentially in subscription order.
- Publishing uses a subscriber snapshot taken when publication starts. Subscribing or unsubscribing during publication affects later publications, not the current one.
- Cancellation is observed before each subscriber is invoked. Cancellation-aware subscribers receive the token passed to `PublishAsync`.
- Static handlers remain alive for the lifetime of the event source. Instance handlers, including capturing lambdas, are held weakly and do not need explicit unsubscription to become collectible.
- Exceptions from synchronous handlers propagate as their original exception type. Exceptions from asynchronous handlers are propagated after the returned task is awaited.
- Multicast delegates subscribe each invocation independently and can be unsubscribed as a group.
- Publication uses a subscriber snapshot captured when it starts. Subscribing or unsubscribing during publication
affects later publications, not the current one.
- Cancellation is checked before publication starts and before each subscriber is invoked. Cancellation-aware handlers
receive the token passed to `PublishAsync`.
- Static handlers remain alive for the lifetime of the event source. Instance handlers, including capturing lambdas, are
held weakly and do not need explicit unsubscription to become collectible.
- Synchronous handler exceptions propagate unchanged. Asynchronous handler exceptions propagate after the returned task
is awaited.
- Each invocation in a multicast delegate is subscribed independently and can be unsubscribed as a group.

## Installation

Install the latest stable package via NuGet:
Install the package via NuGet:

```sh
dotnet add package ByteAether.WeakEvent
```

Use the `--version` option to specify a [preview version](https://www.nuget.org/packages/ByteAether.WeakEvent/absoluteLatest) to install.
Use the `--version` option to specify
a [preview version](https://www.nuget.org/packages/ByteAether.WeakEvent/absoluteLatest) to install.

## Usage

Expand All @@ -53,14 +74,14 @@ Use the `--version` option to specify a [preview version](https://www.nuget.org/
```csharp
using ByteAether.WeakEvent;

// Create an instance of the weak event without event data
// Create an event without payload data.
var myEvent = new WeakEvent();

// Create a subscriber and subscribe
// Create and subscribe a handler.
var subscriber = () => Console.WriteLine("Event received!");
myEvent.Subscribe(subscriber);

// Raise the event
// Publish the event.
await myEvent.PublishAsync();
```

Expand All @@ -69,14 +90,14 @@ await myEvent.PublishAsync();
```csharp
using ByteAether.WeakEvent;

// Create an instance of the weak event with event data
// Create an event with payload data.
var myEvent = new WeakEvent<MyEventData>();

// Create a subscriber and subscribe
// Create and subscribe a handler.
var subscriber = (MyEventData data) => Console.WriteLine("Received: " + data.Message);
myEvent.Subscribe(subscriber);

// Raise the event
// Publish the event.
await myEvent.PublishAsync(new MyEventData("Hello, World!"));

// Define your event data
Expand All @@ -86,39 +107,47 @@ public record MyEventData(string Message);
## API

### `WeakEvent`
* `SubscriberCount`\
Number of alive subscribers currently registered to the event.
* `Subscribe(Action handler)`\
`Subscribe(Func<Task> handler)`\
`Subscribe(Func<CancellationToken, Task> handler)`\
Subscribes the specified handler to the event. A multicast delegate subscribes each invocation. The handlers will be invoked when the event is raised, provided that their targets are still alive.
* `Unsubscribe(Action handler)`\
`Unsubscribe(Func<Task> handler)`\
`Unsubscribe(Func<CancellationToken, Task> handler)`\
Unsubscribes the specified handler from the event. A multicast delegate unsubscribes all matching invocations.
* `PublishAsync(CancellationToken cancellationToken = default)`\
Raises the event by invoking all live subscribers. Dead subscribers (whose targets have been garbage-collected) are removed.

* `SubscriberCount`\
Number of live subscribers currently registered.
* `Subscribe(Action handler)`\
`Subscribe(Func<Task> handler)`\
`Subscribe(Func<CancellationToken, Task> handler)`\
Subscribes the handler. Each invocation in a multicast delegate is subscribed independently. Live handlers are invoked
when the event is published.
* `Unsubscribe(Action handler)`\
`Unsubscribe(Func<Task> handler)`\
`Unsubscribe(Func<CancellationToken, Task> handler)`\
Unsubscribes the handler and returns whether at least one matching invocation was removed. A multicast delegate
unsubscribes all matching invocations.
* `PublishAsync(CancellationToken cancellationToken = default)`\
Invokes live subscribers sequentially and removes dead subscribers.

### `WeakEvent<TEvent>`
* `SubscriberCount`\
Number of alive subscribers currently registered to the event.
* `Subscribe(Action<TEvent> handler)`\
`Subscribe(Func<TEvent, Task> handler)`\
`Subscribe(Func<TEvent, CancellationToken, Task> handler)`\
Subscribes the specified handler to the event. A multicast delegate subscribes each invocation. The handlers will be invoked when the event is raised, provided that their targets are still alive.
* `Unsubscribe(Action<TEvent> handler)`\
`Unsubscribe(Func<TEvent, Task> handler)`\
`Unsubscribe(Func<TEvent, CancellationToken, Task> handler)`\
Unsubscribes the specified handler from the event. A multicast delegate unsubscribes all matching invocations.
* `PublishAsync(TEvent eventData, CancellationToken cancellationToken = default)`\
Raises the event by invoking all live subscribers with the provided event data. Dead subscribers (whose targets have been garbage-collected) are removed.

* `SubscriberCount`\
Number of live subscribers currently registered.
* `Subscribe(Action<TEvent> handler)`\
`Subscribe(Func<TEvent, Task> handler)`\
`Subscribe(Func<TEvent, CancellationToken, Task> handler)`\
Subscribes the handler. Each invocation in a multicast delegate is subscribed independently. Live handlers are invoked
when the event is published.
* `Unsubscribe(Action<TEvent> handler)`\
`Unsubscribe(Func<TEvent, Task> handler)`\
`Unsubscribe(Func<TEvent, CancellationToken, Task> handler)`\
Unsubscribes the handler and returns whether at least one matching invocation was removed. A multicast delegate
unsubscribes all matching invocations.
* `PublishAsync(TEvent eventData, CancellationToken cancellationToken = default)`\
Invokes live subscribers sequentially with `eventData` and removes dead subscribers.

## Contributing

We welcome all contributions! You can:

* **Open a Pull Request:** Fork the repository, create a branch, make your changes, and submit a pull request to the `main` branch.
* **Report Issues:** Found a bug or have a suggestion? [Open an issue](https://github.com/ByteAether/WeakEvent/issues) with details.
* **Open a Pull Request:** Fork the repository, create a branch, make your changes, and submit a pull request to the
`main` branch.
* **Report Issues:** Found a bug or have a suggestion? [Open an issue](https://github.com/ByteAether/WeakEvent/issues)
with details.

Thank you for helping improve the project!

Expand Down
Binary file removed assets/header.png
Binary file not shown.
Binary file added assets/header_weakevent.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed assets/logo.png
Binary file not shown.
Binary file added assets/logo_weakevent.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
31 changes: 19 additions & 12 deletions src/.editorconfig
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
# Remove the line below if you want to inherit .editorconfig settings from higher directories
root = true

# csproj files
[*.csproj]
# Indentation and spacing
indent_size = 2
indent_style = space
tab_width = 2

# C# files
[*.cs]

Expand Down Expand Up @@ -116,7 +123,7 @@ csharp_style_conditional_delegate_call = true:suggestion
# Modifier preferences
csharp_prefer_static_anonymous_function = true:suggestion
csharp_prefer_static_local_function = true:suggestion
csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async
csharp_preferred_modifier_order = public, private, protected, internal, file, static, extern, new, virtual, abstract, sealed, override, readonly, unsafe, required, volatile, async
csharp_style_prefer_readonly_struct = true:suggestion
csharp_style_prefer_readonly_struct_member = true:suggestion

Expand Down Expand Up @@ -229,39 +236,39 @@ dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case

dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.interface.required_modifiers =

dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =
dotnet_naming_symbols.types.required_modifiers =

dotnet_naming_symbols.non_field_members.applicable_kinds = property, method, event
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
dotnet_naming_symbols.non_field_members.required_modifiers =

dotnet_naming_symbols.private_property_field.applicable_kinds = property, field
dotnet_naming_symbols.private_property_field.applicable_accessibilities = private, protected, protected_internal, private_protected
dotnet_naming_symbols.private_property_field.required_modifiers =
dotnet_naming_symbols.private_property_field.required_modifiers =

dotnet_naming_symbols.private_static_property_field.applicable_kinds = property, field
dotnet_naming_symbols.private_static_property_field.applicable_accessibilities = private, protected, protected_internal, private_protected
dotnet_naming_symbols.private_static_property_field.required_modifiers = static

# Naming styles

dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case

dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case

dotnet_naming_style.begins_with__.required_prefix = _
dotnet_naming_style.begins_with__.required_suffix =
dotnet_naming_style.begins_with__.word_separator =
dotnet_naming_style.begins_with__.required_suffix =
dotnet_naming_style.begins_with__.word_separator =
dotnet_naming_style.begins_with__.capitalization = camel_case

[*.{cs,vb}]
Expand Down
26 changes: 14 additions & 12 deletions src/WeakEvent.Tests/WeakEventGenericTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
namespace ByteAether.WeakEvent.Tests;
using System.Diagnostics.CodeAnalysis;

namespace ByteAether.WeakEvent.Tests;

public class WeakEventGenericTests
{
Expand Down Expand Up @@ -37,8 +39,7 @@ public async Task PublishAsync_WithCancelledToken_ThrowsOperationCanceledExcepti
await cts.CancelAsync();

// Assert that publishing an event with the canceled token throws the expected exception.
await Assert.ThrowsAnyAsync<OperationCanceledException>(
() => weakEvent.PublishAsync("Test event", cts.Token)
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => weakEvent.PublishAsync("Test event", cts.Token)
);
Assert.False(handlerInvoked, "The subscribed handler should not be invoked when cancellation is requested.");
}
Expand Down Expand Up @@ -120,14 +121,13 @@ public async Task CancellationTokenHandler_DoesNotAlterArgumentsForFollowingHand
var tokenHandlerCalled = false;
var syncHandlerCalled = false;

weakEvent.Subscribe(
(string _, CancellationToken _) =>
weakEvent.Subscribe((_, _) =>
{
tokenHandlerCalled = true;
return Task.CompletedTask;
}
);
weakEvent.Subscribe((string _) => syncHandlerCalled = true);
weakEvent.Subscribe(_ => syncHandlerCalled = true);

await weakEvent.PublishAsync("Test event");

Expand All @@ -136,17 +136,18 @@ public async Task CancellationTokenHandler_DoesNotAlterArgumentsForFollowingHand
}

[Fact]
[SuppressMessage("ReSharper", "AccessToDisposedClosure")]
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);
weakEvent.Subscribe(_ => cancellationTokenSource.Cancel());
weakEvent.Subscribe(_ => secondHandlerCalled = true);

await Assert.ThrowsAnyAsync<OperationCanceledException>(
() => weakEvent.PublishAsync("Test event", cancellationTokenSource.Token)
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
weakEvent.PublishAsync("Test event", cancellationTokenSource.Token)
);
Assert.False(secondHandlerCalled);
}
Expand All @@ -158,7 +159,7 @@ public async Task Subscribe_MulticastHandler_SubscribesAndUnsubscribesAllInvocat
var invocationCount = 0;
Action<string> firstHandler = _ => invocationCount++;
Action<string> secondHandler = _ => invocationCount++;
Action<string> combinedHandler = firstHandler + secondHandler;
var combinedHandler = firstHandler + secondHandler;

weakEvent.Subscribe(combinedHandler);
Assert.Equal(2, weakEvent.SubscriberCount);
Expand Down Expand Up @@ -225,7 +226,8 @@ public void MultipleHandlers_CorrectCount()

// Stage 2 - Add local handler
void syncHandler(string _)
{ }
{
}

weakEvent.Subscribe(syncHandler);

Expand Down
Loading