DEV Community

Cover image for 🖇️ Smart Event Handling in .NET: Weak References & Pub-Sub Explained
GigAHerZ
GigAHerZ

Posted on • Originally published at byteaether.github.io

🖇️ Smart Event Handling in .NET: Weak References & Pub-Sub Explained

This article was originally published on the ByteAether Blog. It has been republished here with minor edits for clarity and conciseness.

In modern application development, event-driven programming is essential—but it comes with challenges. One common issue is memory leaks caused by lingering event subscriptions. In my latest article, I explore how the weak event pattern combined with publish–subscribe architectures provides a robust solution for this problem.

What’s the Weak Event Pattern?

Normally, when a publisher holds a reference to a subscriber via event delegates, the subscriber won’t be garbage collected even when it’s no longer needed. The weak event pattern uses weak references, which let the garbage collector clean up subscribers automatically. This results in:

  • Better Memory Efficiency: Subscribers won’t block memory cleanup.
  • Decoupled Design: Publishers and subscribers remain independent.
  • Less Manual Cleanup: Reduced risk of forgetting to unsubscribe.

A Glimpse into the Implementation

Consider a simple example in C#:

public class Publisher
{
    private List<WeakReference<EventHandler>> _handlers = new List<WeakReference<EventHandler>>();

    public void Subscribe(EventHandler handler)
    {
        _handlers.Add(new WeakReference<EventHandler>(handler));
    }

    public void RaiseEvent()
    {
        foreach (var weakHandler in _handlers)
        {
            if (weakHandler.TryGetTarget(out EventHandler handler))
            {
                handler.Invoke(this, EventArgs.Empty);
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, the publisher holds weak references to event handlers, allowing the garbage collector to reclaim memory once subscribers are no longer in use.

The Power of Publish–Subscribe with Weak References

Integrating weak references into a publish–subscribe model means even if a subscriber forgets to unsubscribe, it won’t prevent memory cleanup. This approach is invaluable, especially in long-running applications and modern frameworks like Blazor.

To simplify this process, I developed the ByteAether.WeakEvent library. This NuGet package encapsulates these best practices, making it easy to manage event subscriptions without worrying about memory leaks.

Conclusion

By leveraging weak-referenced event managers, you can build more robust and maintainable .NET applications. The combination of weak references and the publish–subscribe pattern ensures that your application remains memory efficient while reducing the complexity of manual unsubscription.

Curious to dive deeper? Check out the full article for an in-depth discussion, practical examples, and more insights into the design behind the WeakEvent library: Read the full article.

Happy coding!

This article was originally published on the ByteAether Blog. It has been republished here with minor edits for clarity and conciseness.

Top comments (0)