Click here to Skip to main content
15,888,802 members
Articles / Programming Languages / C#
Tip/Trick

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 7.3K   7   3
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
victorbos4-Oct-21 5:53 
QuestionMessage Closed Pin
1-Oct-21 1:04
NEHA 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 
This is a great inspiring article. I am pretty much pleased with your good work. You put really very helpful information. Keep it up once again.
PraiseHelpful Pin
DaveMathews30-Sep-21 2:19
DaveMathews30-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.