Reputation: 2070
My application loads an appropriate UserControl onto the canvas depending on some built in logic.
The control on occasion need to be replaced by another UserControl.
To unload the control in code I detached it from it's parent, however I noticed (via the debug window) the processes within the control were still active.
I then subscribed to the Unloaded event and stopped the timers which were running in the user control when the event was raised.
Is this the correct way to handle this? How should I ensure this instance of the UserControl is gone and not still working away in the background?
How I'm loading the UserControl
var arp = new CisDeparturesPanel(_config.CrsCode);
PanelContainer.Children.Add(arp);
_panel = arp;
How I'm detaching the UserControl
var element = _panel as CisDeparturesPanel;
PanelContainer.Children.Remove(element);
_panel = null;
UnLoaded Event Handler
private void CisDeparturesPanel_OnUnloaded(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Unloaded");
_cacheReadTimer.Stop();
_cacheReadTimer.Dispose();
_displaySwitchTimer.Stop();
_displaySwitchTimer.Dispose();
_timeNowTimer.Stop();
_timeNowTimer.Dispose();
_updateCacheFromLiveData.Stop();
_updateCacheFromLiveData.Dispose();
}
Upvotes: 1
Views: 2145
Reputation: 80
In silverlight you can add an empty finalizer to object you want to check:
public ~ClassToCheck()
{} // set breakpoint here
And invoke GC.Collect();
when you want to check if it's already fully unloaded.
It should be similar in wpf.
Upvotes: 1