C# Event Subscriptions: Strong to Weak Reference Transition in .NET 6+
0 reputation · 29 Jun 2023, 04:49 UTC
Event Subscription Lifetime in C#
A standard C# event holds a delegate whose Target property strongly references the subscriber. While the publisher remains alive, the subscriber cannot be garbage collected, even after all application references to the subscriber are dropped.
Transition to Weak Listeners
Replacing explicit -= unsubscription in IDisposable.Dispose with a ConditionalWeakTable-based weak listener changes the lifetime boundary. In .NET 6 and later, the table permits key collection but does not guarantee handler persistence during an active event dispatch.
The unresolved behavior is whether a weakly held subscriber can be collected while the publisher is actively raising the event.
- Can the subscriber be finalized during an active event invocation when no external strong reference exists?
- What compatibility implications arise from replacing manual unsubscription with
ConditionalWeakTablein .NET 6+?