我正在通过下面的代码生成新窗口并在那里显示一个网页,然后将其关闭。但过了一会儿,软件给出了内存不足的异常。所以发生了内存泄漏。可能是什么原因以及如何解决?谢谢你。
这就是我如何启动新窗口。我正在做一个循环,因此正在启动数千个新窗口。正如您在 60 秒后看到的那样,新窗口会自行关闭。
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();
}
}