Skip to content

Instantly share code, notes, and snippets.

@cisoun
Created January 19, 2018 18:17
Show Gist options
  • Save cisoun/ae4fc4517e21f43df2448f970d7a7d5b to your computer and use it in GitHub Desktop.
Save cisoun/ae4fc4517e21f43df2448f970d7a7d5b to your computer and use it in GitHub Desktop.
Unregister all delegates from a EventHandler
/// <summary>
/// Unregisters all delegates from an EventHandler.
/// </summary>
/// <param name="eventHandler">EventHandler to clear.</param>
public static void UnregisterAllDelegates(ref EventHandler eventHandler)
{
// Cancel if already cleared.
if (eventHandler == null)
return;
// Clear the EventHandler.
var invocations = eventHandler.GetInvocationList();
foreach (var invocation in invocations)
eventHandler -= invocation as EventHandler;
// Release the handler.
eventHandler = null;
}
/// <summary>
/// Unregisters all delegates from an EventHandler.
/// </summary>
/// <param name="eventHandler">EventHandler to clear.</param>
/// <typeparam name="T">Type of EventHandler.</typeparam>
public static void UnregisterAllDelegates<T>(ref EventHandler<T> eventHandler)
{
// Cancel if already cleared.
if (eventHandler == null)
return;
// Clear the EventHandler.
var invocations = eventHandler.GetInvocationList();
foreach (var invocation in invocations)
eventHandler -= invocation as EventHandler<T>;
// Release the handler.
eventHandler = null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment