Weak event + lambda = memory leak?

Weak event play

public class Test
{
    public Test(Button button)
    {
        WeakEventManager<Button, RoutedEventArgs>.AddHandler(button, nameof(Button.Click),
            (s, e) => MessageBox.Show("Tada"));
    }
}

      

with this code

Test _test;
void ButtonCreate_Click(object sender, RoutedEventArgs e) => _test = new Test(button);
void ButtonDelete_Click(object sender, RoutedEventArgs e) => _test = null;
void ButtonGC_Click(object sender, RoutedEventArgs e)
{
    GC.Collect(2);
    GC.WaitForPendingFinalizers();
}

      

It looks like the lifetime of this event handler is longer than I expected.

Here is a demo where I click Create3 times, then Deleteand GC, but clicking the button still executes all event handlers:

My question is, what is wrong here?


There is no such problem without lambda

public class Test
{
    public Test(Button button)
    {
        WeakEventManager<Button, RoutedEventArgs>.AddHandler(button,
            nameof(Button.Click), Button_Click);
    }
    void Button_Click(object sender, RoutedEventArgs e) => MessageBox.Show("Tada");
}

      

but there is another problem where the event handler is still called after Deleteif not pressed GC!

+3


source to share





All Articles