There is a method Something I run it 100,500 times, but the System.Windows.Window object does not disappear from memory.

 private void Something() { Thread t = new Thread(()=> { Window w = new Window() { Width = 1024, Height = 768 }; w.Show(); Thread.Sleep(1000); w.Close(); }); t.SetApartmentState(ApartmentState.STA); t.Priority = ThreadPriority.Normal; t.Start(); GC.Collect(); } 
  • one
    social.msdn.microsoft.com/Forums/ru-RU/...here is a very useful info on the release of window resources .. - MrModest
  • @ Mr.Modest didn’t find an answer in the article except “don’t worry about 20 meters,” but my gig wins out, and the farther away the more - Dmitry Chistik
  • Try creating your own class that will inherit from Window and implement IDisposable. - MrModest
  • And you can ask why you need to create so many windows? Why is it impossible to open and close the same window every time? - MrModest
  • @ Mr.Modest inheritance does not solve the problem, the window will not be deleted, unless you know what to write in Dispose. The task is broader than I wrote in the topic, it is difficult to explain, and it’s impossible to open the window that was closed. - Dmitry Chistik

1 answer 1

Opening a window in your own thread is not a good idea, usually only calculations are allocated to the stream. However, in this example, the memory will be freed if you subscribe to the Closed window event and call Dispatcher.CurrentDispatcher.BeginInvokeShutdown , and after closing the window call Dispatcher.Run . In actual use, Dispatcher.Run is called after the window is opened, and closing occurs by user action, not programmatically.

 private void Something() { var t = new Thread(() => { var w = new Window() { Width = 1024, Height = 768 }; w.Show(); w.Closed += (s, ex) => Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background); Thread.Sleep(1000); w.Close(); Dispatcher.Run(); }); t.SetApartmentState(ApartmentState.STA); t.Priority = ThreadPriority.Normal; t.Start(); GC.Collect(); } 

Information from here .

  • one
    Tadam! I will explain this waiting window so to speak. It just has to be in another thread. Thanks for the answer. - Dmitry Chistik