C# Using statement does not work on System.Management.ManagementBaseObject - by Michael Graczyk

Status : 


Sign in
to vote
ID 757707 Comments
Status Active Workarounds
Type Bug Repros 4
Opened 8/9/2012 11:30:02 PM
Access Restriction Public


It appears that ManagementBaseObject implements `Dispose` incorrectly, and as a result the c# using statement does not properly dispose instances of that class.

Here's the implementation of Dispose:

        public new void Dispose() 
            if (_wbemObject != null) 
                _wbemObject = null;

Notice the "new" keyword?  From my knowledge this is not the correct way to derive from Component.  The BCL people seem to agree, with this comment (taken from Component.cs):

    ///    <para>
    ///    For base classes, you should never override the Finalier (~Class in C#) 
    ///    or the Dispose method that takes no arguments, rather you should 
    ///    always override the Dispose method that takes a bool.
    ///    </para> 
    ///    <code>
    ///    protected override void Dispose(bool disposing) {
    ///        if (disposing) {
    ///            if (myobject != null) { 
    ///                myobject.Dispose();
    ///                myobject = null; 
    ///            } 
    ///        }
    ///        if (myhandle != IntPtr.Zero) { 
    ///            NativeMethods.Release(myhandle);
    ///            myhandle = IntPtr.Zero;
    ///        }
    ///        base.Dispose(disposing); 
    ///    }

It appears that rather than declaring "new void Dispose()", ManagementBaseObject should have declared "override void Dispose(bool)".

Because of the "new" implementation of Dispose, the using statement calls only the explicit interface implementation, and hence only the Component.Dispose() method.

I do not have the .NET 4.5 reference source, so I cannot verify that this issue still exists, but it should easy to check (Simply look for the "new" keyword in the "Dispose" prototype.  If it is still there, the bug is still there).

See this Stack Overflow question for more details.  http://stackoverflow.com/questions/11896282/c-sharp-using-clause-fails-to-call-dispose
Sign in to post a comment.
Posted by tasoss on 6/17/2014 at 4:12 AM
I don't really understand why haven't you fixed this yet???
Posted by 佐祐理 on 1/20/2013 at 6:02 PM
The "new void Dispose()" method is added with breaking IDisposable interface at .NET 2.0 SP1. And it still exists in .NET 4.5.
Posted by Microsoft on 8/10/2012 at 1:12 AM
Thanks for your feedback.

We are rerouting this issue to the appropriate group within the Visual Studio Product Team for triage and resolution. These specialized experts will follow-up with your issue.
Posted by Microsoft on 8/9/2012 at 11:50 PM
Thank you for your feedback, we are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(http://support.microsoft.com)