Class WeakEventController
Implements a weak event listener that allows the owner to be garbage collected if it is the only remaining link is an event handler.
Namespace: Neon.Common
Assembly: Neon.Common.dll
Syntax
public static class WeakEventController
Remarks
This class is intended to be a drop-in replacement for the WeakEventManager class that is available in .NET 4.5 but is not currently present in the Xamarin Mono class libraries. Use the AddHandler<TEventSource, TEventArgs>(TEventSource, string, EventHandler<TEventArgs>) and RemoveHandler<TEventSource, TEventArgs>(TEventSource, string, EventHandler<TEventArgs>) to add or remove event handlers.
note
Important: Take care to remove any handlers when an event listener instance is disposed and/or finalized. Neglecting to do this will orhpan the objects WeakEventController uses to track the handler references.
This code was adapted from a Code Project article by Samuel Cragg called WeakEventManager for WinRT. The code is licensed under the The Code Project Open License (CPOL).
I enhanced the code by making it threadsafe.
Methods
AddHandler<TEventSource, TEventArgs>(TEventSource, string, EventHandler<TEventArgs>)
Adds the specified event handler to the specified event.
Declaration
public static void AddHandler<TEventSource, TEventArgs>(TEventSource source, string eventName, EventHandler<TEventArgs> handler)
Parameters
Type | Name | Description |
---|---|---|
TEventSource | source | The source object that raises the specified event or |
string | eventName | The name of the event to subscribe to. |
EventHandler<TEventArgs> | handler | The delegate that handles the event. |
Type Parameters
Name | Description |
---|---|
TEventSource | The type that raises the event. |
TEventArgs | The type that holds the event data. |
RemoveHandler<TEventSource, TEventArgs>(TEventSource, string, EventHandler<TEventArgs>)
Removes the specified event handler from the specified event.
Declaration
public static void RemoveHandler<TEventSource, TEventArgs>(TEventSource source, string eventName, EventHandler<TEventArgs> handler)
Parameters
Type | Name | Description |
---|---|---|
TEventSource | source | The source object that raises the specified event, or null if it's a static event. |
string | eventName | The name of the event to remove the handler from. |
EventHandler<TEventArgs> | handler | The delegate to remove. |
Type Parameters
Name | Description |
---|---|
TEventSource | The type that raises the event. |
TEventArgs | The type that holds the event data. |