Now I understand that when I have finished with a resource that implements IDisposable
, I should call the Dispose()
method to clean up the resources.
To what extent should I be doing this.
My example is:
I am creating a NotifyIcon
in code, so I do something like this:
var icon = new Icon(...);
var contextMenu = new ContextMenu(...);
var contextMenuButton1 = new MenuItem(...);
var contextMenuButton2 = new MenuItem(...);
var contextMenuButton3 = new MenuItem(...);
// ...
var notifyIcon = new NotifyIcon(...);
All of these have a Dispose()
method. Normally I would only keep reference to the notifyIcon
and just dispose that.
However, it won't dispose of the Icon or the Context Menu or its items, so should I actually be keeping a reference to everything, or at least have a List<IDisposable>
?
OR can I assume because of the scope of these that the garbage collector will call dispose on these for me (when I dispose of the NotifyIcon)?
From MSDN: `
If you use the constructor that takes a container (typically a
System.ComponentModel.Container
) owned by aForm
), then Dispose will be called when the container is disposed - i.e. when the Form is closed.The examples in the MSDN documentation linked above use a Form's container in this way.
If you use the default constructor, there is no container, and you will have to manage the lifetime of the NotifyIcon yourself, and dispose it when you're finished.