WPF: Should I manually call Close in windows opened by the ShowDialog method?

The fact is that WPF Window does not implement the IDisposable interface, which led me to believe that I do not need to manually manage it when I open it by calling ShowDialog (), but the first comment on this MSDN page says otherwise. Does anyone know the truth?

+4
source share
2 answers

Only if you open the window using Show () instead of ShowDialog ().

From the documentation:

If the window opened by calling ShowDialog, and with the button with the IsCancel property set to true, automatically closes when the button is pressed or ESC is pressed. If the window was opened using Show, however, Close should be explicitly called, for example, from the Click event handler for the button.

and

Closing a window raises the Closing event. If the close event is not canceled, the following occurs:

  • The window is removed from Application.Windows (if the application object exists).
  • The window is removed from the Owner window if the owner / owner relationship was established before the Window window was shown and after opening the Owner window.
  • Closed event closed.
  • Unmanaged resources created in the window are installed.
  • If ShowDialog is called to display the window, ShowDialog is returned.
+5
source

How about the code below? implementing IDisposable in your form and removing all event handlers. However, is Microsoft already doing this on Close ()?

Does the GC.Collect Reference Help?

Some links and related posts:

What is the correct way to recycle a WPF window?

What is the correct way to recycle a WPF window?

/// <summary> /// Interaction logic for MyForm.xaml /// </summary> public partial class MyForm: IDisposable { public MyForm() {} private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { Dispose(); } public void Dispose() { try{ _resourcescollection.Clear(); _resourcescoll = null; //close other resources } catch(exception ex) {} EventHelper.RemoveAllEventHandlers(_resources); EventHelper.RemoveAllEventHandlers(_timer); EventHelper.RemoveAllEventHandlers(_etc); EventHelper.RemoveAllEventHandlers(this); } ~MyForm() { Dispose(); } } 
0
source

Source: https://habr.com/ru/post/1301107/


All Articles