In my WPF MVVM application, I am subscribing to PreviewKeyUp
and PreviewKeyDown
in UserControl1.xaml.cs
as such:
UserControl1_Loaded(object sender, RoutedEventArgs e)
{
var window = Window.GetWindow(this);
window.PreviewKeyUp = UserControl1_PreviewKeyUp;
window.PreviewKeyDown = UserControl1_PreviewKeyDown;
}
Should I worry about a memory leak? Do I have to unsubscribe from these events in the Unloaded
event or will the GC take care of it?
CodePudding user response:
Should I worry about a memory leak?
Only if the parent window that publish the events lives longer than the UserControl
that subscribes to the event.
Do I have to unsubscribe from these events in the Unloaded event or will the GC take care of it?
You need to unexplicitly unsubscribe for the window not to keep the UserControl
instance alive. Again, this is not an issue if the both the window and the UserControl
become eligible for garbage collection at the same time.
The garbage collector never unsubscribe from any events for you though.