Playing with weak event
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 this event handler life time is longer than I'd expect.
Here is a demo where I click Create 3 times, then Delete and GC, but clicking the button will still execute all event handlers:
My question is what is wrong here?
Without lambda there is no such issue
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 another problem arise, where event handler is still called after Delete unless GC is pressed!