Sauron
Sauron

Reputation: 16903

When to call Dispose() method in WPF application

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?

Upvotes: 9

Views: 18725

Answers (4)

tm1
tm1

Reputation: 1319

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);
    }
}

Upvotes: 1

Daniel Earwicker
Daniel Earwicker

Reputation: 116674

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.

Upvotes: 8

terR0Q
terR0Q

Reputation: 1367

If that control is a part of some IContainer (that's the common model in .NET) than your controls just needs implementation of IDisposable. Thus Dispose() will be called automatically when it is appropriate time.

Upvotes: 0

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

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.

Upvotes: 2

Related Questions