Click here to Skip to main content
15,434,147 members
Articles / Programming Languages / C#
Tip/Trick
Posted 29 Sep 2021

Tagged as

Stats

4.8K views
6 bookmarked

Clear All Events Listeners of an Instance or Static Event

Rate me:
Please Sign up or sign in to vote.
5.00/5 (9 votes)
29 Sep 2021MIT
How to clear all events is quite simple. It needs a finger of reflection...
This snippet will help you if you need to cleanup events. In a normal way, you have to use += or -=, or use WeakEventHandler().AddHandler or RemoveHandler. But sometimes, you could need a harder way!

Introduction

We had the need to cleanup a WPF Visual tree on windows closing. To do that, we developed a WPF Behavior on the Window component.

On closing, this behavior just ran across the visual tree of the window. Take each component and to this:

  • Clear all bindings
  • Clear all event listeners (static or not)
  • Set the dataContext to null

This helps the GC to collect speedily...

Using the Code

The code to do the clear events part is the following:

C#
public static void ClearEvents(object instance)
{
    var eventsToClear = instance.GetType().GetEvents(
        BindingFlags.Public | BindingFlags.NonPublic
        | BindingFlags.Instance | BindingFlags.Static);

    foreach (var eventInfo in eventsToClear)
    {
        var fieldInfo = instance.GetType().GetField(
            eventInfo.Name, 
            BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
            
        if (fieldInfo.GetValue(instance) is Delegate eventHandler)
            foreach (var invocatedDelegate in eventHandler.GetInvocationList())
                eventInfo.GetRemoveMethod(fieldInfo.IsPrivate).Invoke(
                    instance, 
                    new object[] { invocatedDelegate });
    }
}

Points of Interest

Reflection is a very powerful tool, but this must not be the main way. This must only be used in critical scenarios.

Be careful of that!

History

  • 29th September, 2021: Version 1

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Web Developer
France France
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWhy do you say "This must only be used in critical scenarios. Be careful of that!" Pin
victorbos4-Oct-21 5:53
Membervictorbos4-Oct-21 5:53 
I definitely learned something new from your article. Rose | [Rose]

Background: Although likely not relevant to my question, I am learning how to use WebView2, and the Microsoft's example, suggests adding a bunch of event handlers (though with very little explanation). One of them is an event handler for "ContentLoading".

So if I merely want to remove "ContentLoading" event handler why is your approach (i.e., using code suitably modified) more dangerous than the -= approach?

QuestionMessage Closed Pin
1-Oct-21 1:04
MemberNEHA SINGH Oct20211-Oct-21 1:04 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA30-Sep-21 20:37
professionalȘtefan-Mihai MOGA30-Sep-21 20:37 
PraiseHelpful Pin
DaveMathews30-Sep-21 2:19
MemberDaveMathews30-Sep-21 2:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.