Search code examples
c#wpfmemory-leaksout-of-memorynew-window

Creating new window then closing it causes memory leak


I am generating new windows via the code below and displaying a webpage there and then close it. But after a while software gives out of memory exception. So there is memory leak happening. What might be the cause and how to solve it ? Thank you.

This is how do i start new window . i am doing a loop so there are being started thousands of new windows. As you can see after 60 seconds new window get itself close.

NewWindowThread<TitleWindow, string>(c => new TitleWindow(c), "the url that is going to be displayed at new window");

private void NewWindowThread<T, P>(Func<P, T> constructor, P param) where T : Window
{
    Thread thread = new Thread(() =>
    {
         T w = constructor(param);
         w.Show();
         w.Closed += (sender, e) => w.Dispatcher.InvokeShutdown();
         System.Windows.Threading.Dispatcher.Run();
    });
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
}

public class TitleWindow : Window
{
    WebBrowser webnew = new WebBrowser();
    public TitleWindow(string srUrl)
    {              
         DockPanel dk = new DockPanel();
         dk.Width = 900;
         dk.Height = 600;
         this.AddChild(dk);
         webnew.Navigated += new NavigatedEventHandler(wbMain_Navigated);

         System.Windows.Threading.DispatcherTimer dispatcherTimer3 = new System.Windows.Threading.DispatcherTimer();
         dispatcherTimer3.Tick += new EventHandler(dispatcherTimer_Tick3);
         dispatcherTimer3.Interval = new TimeSpan(0, 0, 0, 60, 0);
         dispatcherTimer3.Start();

         webnew.Height = 600;
         webnew.Width = 900;
         dk.Children.Add(webnew);
         webnew.Navigate(srUrl);

         this.WindowState = WindowState.Minimized;
    }

    void dispatcherTimer_Tick3(object sender, EventArgs e)
    {             
         this.Close();
    }
}

Solution

  • I immediately suspect that the WebBrowser control is not releasing it's resources when the window is closed as you are not calling it's Dispose() method. The WebBrowser control is a thin wrapper around the ActiveX MSHTML control.

    Add a callback on the window Closing or Closed events to do this. e.g. webnew.Dispose().