How to remove all eventhandler [duplicate]
Asked Answered
T

2

13

Lets say we have a delegate

public delegate void MyEventHandler(string x);

and an event handler

public event MyEventHandler Something;

we add multiple events..

for(int x = 0; x <10; x++)  
{
   this.Something += HandleSomething;
}

My question is .. how would one remove all methods from the eventhandler presuming one doesn't know its been added 10 (or more or less) times?

Tedious answered 18/3, 2016 at 12:30 Comment(0)
P
27

Simply set the event to null:

this.Something = null;

It will unregister all event handlers.

Piccalilli answered 18/3, 2016 at 12:32 Comment(6)
I always thought one had to manually remove them, but surprisingly.. this does work.. I did something similar the accepted answer on #448321Tedious
It seems to me that this practice is well worth doing inside a class' Dispose(bool) method, but I don't see references to this practice anywhere. Is my thinking sound?Groupie
I think that could be a good idea, but you should be careful not to bloat your code either, which could end up leading to bugs instead of fixing them. I have a method where I pass in the register and unregister action and on calling Dispose it executes all unregister actions. @PieterGeerkensPiccalilli
I thought this wouldn't be possible because of this : https://mcmap.net/q/156807/-how-can-i-clear-event-subscriptions-in-c Or is it possible in that particular case ?Clouet
@Clouet this is from within the class itself. So it is possible.Piccalilli
Oh that's great then, I'll try it out! ThanksClouet
A
0

As pseudo idea:

C#5 <

class MyDelegateHelperClass{
    public static void RemoveEventHandlers<TModel, TItem>(MulticastDelegate m, Expression<Func<TModel, TItem>> expr) {


                EventInfo eventInfo= ((MemberExpression)expr.Body).Member as EventInfo;


                Delegate[] subscribers = m.GetInvocationList();

                Delegate currentDelegate;

                for (int i = 0; i < subscribers.Length; i++) {

                    currentDelegate=subscribers[i];
                    eventInfo.RemoveEventHandler(currentDelegate.Target,currentDelegate);

                }
            }
}

Usage:

 MyDelegateHelperClass.RemoveEventHandlers(MyDelegate,()=>myClass.myDelegate);

C#6

public static void RemoveEventHandlers(this MulticastDelegate m){

        string eventName=nameof(m);

        EventInfo eventInfo=m.GetType().ReflectingType.GetEvent(eventName,BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);


        Delegate[] subscribers = m.GetInvocationList();

        Delegate currentDelegate;

        for (int i = 0; i < subscribers.Length; i++) {

            currentDelegate=subscribers[i];
            eventInfo.RemoveEventHandler(currentDelegate.Target,currentDelegate);

        }

    }

Usage:

MyDelegate.RemoveEventHandlers();
Ass answered 5/3, 2018 at 14:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.