When to call Dispose() method in WPF application

16,049

Solution 1

Hardly anything in WPF has a Dispose method. The vast majority of classes encapsulate purely managed information. You can attach an object into the tree (e.g. via a Children.Add method) and you can remove it again - that's how the state management works. It exactly doesn't fit into the IDisposable pattern, because once you've removed a control you can add it again, whereas Dispose means forever (although you could use Dispose to manage it in addition to Add/Remove methods).

A discussion about it on the Microsoft forums.

There are a few things that ought to be IDisposable but aren't, like DispatcherTimer, and there's nothing to stop you from implementing IDisposable on your own classes. It's up to you when to call Dispose; basically when you know you aren't going to be using the object any more.

For a Window you just call Close to close it, and WPF takes care of everything else.

Solution 2

I would say that the same rule applies in WPF applications as in any other .NET applications: if an object implements IDisposable, you should call Dispose when you are done using it. If you dynamically load and unload controls, and they do not implement IDisposable, just setting any references to null (and detaching any event handlers) should be enough for the garbage collector to do its job.

Solution 3

Adhere to CA1001: Let the owning type implement IDisposable.

Renounce the old Windows Forms truth that all controls are IDisposable. Implement and call Dispose yourselves.

sealed partial class MainWindow : IDisposable {
    readonly IDisposable disposable;
    public MainWindow() {
        disposable = ...
    }

    public void Dispose() {
        disposable.Dispose();
    }

    protected override void OnClosed(EventArgs e) {
        Dispose();
        base.OnClosed(e);
    }
}
Share:
16,049
Sauron
Author by

Sauron

Updated on June 17, 2022

Comments

  • Sauron
    Sauron almost 2 years

    I have a simple WPF single window application contains Textboxes and Buttons. And I also use NotifyIcon and DateTimePicker of Windows Forms in WPF window. How can I effectively dispose all the controls?