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

巧了我就是萌 提交于 2019-12-17 15:59:22

问题


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?


回答1:


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)




回答2:


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.




回答3:


Just in case, I'll add my two cents.

My problem was that I didn't do enough troubleshooting. My window was a child window that could be opened, closed, and re-opened, so I added the following to keep it from closing completely:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
  e.Cancel = true;
  this.Hide();
}

However, when Window.Close was called, it only hid the window. I eventually caught on and added the following:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
  e.Cancel = true;
  this.Hide();
}

public void Close() {
  this.Closing -= Window_Closing;
  //Add closing logic here.
  base.Close();
}

This works fine - it removes the event handler preventing the window from being closed, and then closes it.




回答4:


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.



来源:https://stackoverflow.com/questions/568408/what-is-the-correct-way-to-dispose-of-a-wpf-window

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!