The ultimate answer to the question is yes. You have to release the objects held by a ManagementObjectCollection.
Here's why:
If you look into the ManagementObjectCollection.Dispose() method, you'll see it calls Marshal.ReleaseComObject() on 'enumWbem'.
private void Dispose ( bool disposing )
{
if ( disposing )
{
GC.SuppressFinalize (this);
isDisposed = true;
}
Marshal.ReleaseComObject (enumWbem);
}
'enumWbem' is a Runtime Callable Wrapper of the interface IEnumWbemClassObject.
On the implementation example found here they release every object prior to releasing the IEnumWbemClassObject.
Furthermore, on the ManagementBaseObject signature, the Dispose() method looks like this:
public new void Dispose()
{
if (_wbemObject != null)
{
_wbemObject.Dispose();
_wbemObject = null;
}
base.Dispose();
GC.SuppressFinalize(this);
}
Where _wbemObject is a IWbemClassObjectFreeThreaded, so Dispose() will call Marshal.ReleaseComObject(), and base.Dispose() calls the 'Component' class Dispose().
My C# knowledge is week on this one, but this is what the virtual method looks like:
protected virtual void Dispose(bool disposing) {
if (disposing) {
lock(this) {
if (site != null && site.Container != null) {
site.Container.Remove(this);
}
if (events != null) {
EventHandler handler = (EventHandler)events[EventDisposed];
if (handler != null) handler(this, EventArgs.Empty);
}
}
}
}
I know that freeing every single object is a pain, but dealing with COM overall is :D.
You can use a helper class, and structure your code accordingly, to avoid memory leaks.
Hope it helps!
foreach
throughManagementObjectCollections
createsManagementObjectEnumerator
and that should be disposed, too. ugh – Electrodynamics