I am creating window in another thread. After closing the thread some of the resources window is not released from the memory. Because of this growing counter GDI Objects and User Objects in windows task manager. Graphics that not released are font and region. I haven’t idea what is going on…
public class WaitingWindowManager
{
private Thread thread;
private bool canAbortThread = false;
private Window waitingWindow;
public void BeginWaiting()
{
this.thread = new Thread(this.RunThread);
this.thread.IsBackground = true;
this.thread.SetApartmentState(ApartmentState.STA);
this.thread.Start();
}
public void EndWaiting()
{
if (this.waitingWindow != null)
{
this.waitingWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.waitingWindow.Close(); }));
while (!this.canAbortThread) { };
}
this.thread.Abort();
}
public void RunThread()
{
this.waitingWindow = new Window();
this.waitingWindow.Closed += new EventHandler(waitingWindow_Closed);
this.waitingWindow.ShowDialog();
}
void waitingWindow_Closed(object sender, EventArgs e)
{
this.canAbortThread = true;
}
}
And call :
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
WaitingWindowManager waitingWindowManager = new WaitingWindowManager();
waitingWindowManager.BeginWaiting();
Application.Current.Dispatcher.Thread.Join(5000);
waitingWindowManager.EndWaiting();
}
}
Remove your Closed eventhandler in your waitingWindow_Closed Event. It is causing your window to not be disposed. If you manually add events you need to make sure you remove them when finished.
I also noticed another Stackoverflow question that was pertaining to memory leaks in wpf. It referenced this article maybe this will help you.