Search code examples
wpfmemory-leaksdispatchertimer

WPF control retained in memory due to DispatcherTimer EventHandler


Yo

One of my WPF control is retained in memory due to one of its private member. The incriminate member is a DispatcherTimer and the retention is because of the Tick event handler. (This leak was detected with help of the tool ANTS Memory Profiler)

Obviously, I set/remove the handler on load/unload. And the control is unloaded...

void TransportControl_Loaded(object sender, RoutedEventArgs e)
{
  if (m_playheadTimer == null)
  {
    m_playheadTimer = new System.Windows.Threading.DispatcherTimer();
    m_playheadTimer.Tick += PlayheadTimer_Tick;
    m_playheadTimer.Interval = TimeSpan.FromMilliseconds(50);
  }
}

void TransportControl_Unloaded(object sender, RoutedEventArgs e)
{
  if (m_playheadTimer != null)
  {
    if (m_playheadTimer.IsEnabled)
      m_playheadTimer.Stop();

    m_playheadTimer.Tick -= PlayheadTimer_Tick;
  }
}

But still I'm stuck with that trouble (the same as my control is stuck in memory). Any ideas, THX


Solution

  • You should have a look at weak event pattern. It is not an exactly easy topic though.