Do I need to remove this kind of event handler?

If I create a .NET class that subscribes to an event with an anonymous function, for example:

void MyMethod()
{
   Application.Current.Deactivated += (s,e) => { ChangeAppearance(); };
}

Will this event handler be the root so that my class is not garbage collected?

If not, wohoo! But if so, can you show me the delete syntax? Just using - = with the same code seems wrong.

+5
source share
4 answers

You can use the "real" method, as suggested by Simon D., or do this:

EventHandler handler = null;
handler = (s,e) => { 
    Application.Current.Deactivated -= handler;
    ChangeAppearance();
};
Application.Current.Deactivated += handler;

Since this is somewhat ugly and defeats the purpose of using lambda for succin, I will probably go over with refactoring to the method. But it’s good to know what else works.

: , -, handler , , , , .

+3

, , () , , , . , , , , .

. , . , , .

, "" , , :

Application.Current.Deactivated += ChangeAppearance;
Application.Current.Deactivated -= ChangeAppearance;
private void ChangeAppearance(object sender, EventArgs eventArgs)
{
    throw new NotImplementedException();
}
+3

. , .

static class MemoryLeak
{
    static List<Action<int>> list = new List<Action<int>>();
    public static event Action<int> ActivateLeak
    {
        add
        {
            list.Add(value);
        }
        remove
        {
            list.Remove(value);
        }
    }
}

, , , .

class Program
{
    static void Main(string[] args)
    {
        foo f = new foo();
        MemoryLeak.ActivateLeak += o => f.bar();
        f.tryCleanup();
    }
}

class foo
{
    public void bar()
    { }

    public void tryCleanup()
    {
        MemoryLeak.ActivateLeak -= o => bar();
    }
}

"", .

foo f = new foo();
Action<int> callfoo = o => f.bar();
MemoryLeak.ActivateLeak += callfoo;
Action cleanUp = () => MemoryLeak.ActivateLeak -= callfoo;

// Now you can pass around the cleanUp action and call it when you need to unsubscribe from the event.
cleanUp();
+2

This is truly a leak that prevents garbage collection. There are ways to get around this - with WeakReference one of the best.

This link has a good conversation and good answers for you.

+1
source

All Articles