Given the following two constructors of a WPF window
public Constructor1()
{
Loaded += OnLoaded;
void OnLoaded(object? s, EventArgs e)
{
DoWork();
Loaded -= OnLoaded;
}
}
public Constructor2()
{
Loaded += (_, _) => DoWork();
}
The second is more concise and elegant, but it never unregisters the event (explicitly) like Constructor1.
If the Window is open and closed multiple times, does Constructor2 cause a leakage? Why?
Of course I assume Constructor1 does not.
I did some tests with the Loaded event and it looks like when the window is closed, the event handler is unregistered automatically by the garbage collection. In other words it looks as it is safe to use Constructor2 (not explicit unregistering the handler does not cause an event leak as other events like a timed.Tick).