What is the correct way to dispose of a WPF window?

Viewed 69622

I have a WPF window which I am creating from another window by calling Show(), then letting it Close() itself. When the window closes, I expect it to die, call its destructor, and delete all its child elements (such as timers..).

What is the correct way of invoking such an action?

5 Answers

Close() releases all unmanaged resources, and closes all owned Windows.

Any other managed resources you need deterministic disposal of should be handled from the Closed event.

Reference

(note: deleted previous answer, it was a completely wrong guess)

There are very few WPF elements that actually need to be explicitly disposed, unlike in Windows Forms.

In the case of Window, calling Close() is sufficient to dispose all managed and unmanaged resources accorrding to the documentation.

Closing the window and being confident that you have released all resources to it and any of its children will cause all well behaved elements in the logic tree to be garbage collected.

I say "well behaved" because it's theoretically possible to have an element that does something like create a thread that isn't stopped properly, but in practice if you're using the basic WPF framework and well written controls, you should be fine to just release everything.

Regarding resources held by the Window, according to the documentation:

(emphasis added)

Closing a window causes the Closing event to be raised. If the Closing event isn't canceled, the following occurs:

  1. The Window is removed from Application.Windows (if an Application object exists).

  2. The Window is removed from the owner Window if the owner/owned relationship was established before the owned Window was shown and after the owner Window was opened.

  3. The Closed event is raised.

  4. Unmanaged resources created by the Window are disposed.

  5. If ShowDialog was called to show the Window, ShowDialog returns.

I believe this is listed in sequential order.


I'm not sure specifically about the timers sub-question; I don't think the question has enough detail to really answer that.

Related