The ChannelAdam Weak Events Library
Overview
An open source, .NET Standard 2.0 library for events that enforces a weak reference to the event handler.
You may need a Weak Event Pattern in specific circumstances to prevent memory leaks in your event listeners.
Below are the main features of the library. See the linked code for details.
Please contact me if you have any questions.
Getting Started
NuGet Package Installation
To install the ChannelAdam.WeakEvents NuGet package run the following command in the Package Manager Console:
1PM> Install-Package ChannelAdam.WeakEvents
Usage
1using ChannelAdam.Events;
2...
3
4public class ExampleEventOwner
5{
6 private WeakEvent<EventArgs> _myEvent = new WeakEvent<EventArgs>();
7
8 public IWeakEvent<EventArgs> MyEvent
9 {
10 get { return _myEvent; }
11 }
12
13 ...
14
15 protected virtual void OnMyEvent()
16 {
17 _myEvent.Invoke(this, EventArgs.Empty);
18 }
19}
20
21
22public class ExampleEventSubscriber : ChannelAdam.Disposing.DisposableWithDestructor
23{
24 private ExampleEventOwner _eventOwner;
25
26 public ExampleEventSubscriber()
27 {
28 _eventOwner = new ExampleEventOwner()
29 _eventOwner.MyEvent.Subscribe(MyEventHandler);
30 }
31
32 private void MyEventHandler(object sender, EventArgs e)
33 {
34 // MyEvent occurred
35 }
36
37 protected override void DisposeManagedResources()
38 {
39 _eventOwner?.MyEvent?.Unsubscribe(MyEventHandler);
40 }
41}