Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

My question is how the disposing of an object that need to call the Dispose method works. By the way, English is not my native language, so sorry if the there are gramatical errors

I want to get a list of the service that are installed in my system, for that I use WMI. First I get the instances of the Win32_Service using the GetInstance method that are in the ManagementClass that returns a ManagementObjectCollection. But since an object of the ManagementClass needs to call the Dispose method when we don't need it anymore and the same for the ManagementObjectCollection, so here in the code bellow,
C#
var services = new ManagementClass("Win32_Service").GetInstances();

foreach (var service in services)
{
    //Some code here            
    service.Dispose();
}
wmiServiceClass.Dispose();
services.Dispose();


can I assume that the CLR will dispose of the instance of the ManagementClass that it creates for getting the instance or it's better doing it like this

C#
var wmiServiceClass = new ManagementClass("Win32_Service");
var services = wmiServiceClass.GetInstances();

foreach (var service in services)
{
    //Some code here            
    service.Dispose();
}
wmiServiceClass.Dispose();
services.Dispose();


Thanks in advance.
Posted

1 solution

The concern is not clear. Not all types need disposal, only those implementing interface System.IDisposable. Also, confusingly, some types also introduce methods with the same name, not related to this interface. You really need to check up if this interface is implemented and call System.IDisposable.Dispose. The purpose of it can be… anything; this is just a method to do some clean-up. If you don't do this call, you can face different kinds of problems, including unmanaged memory leak. Even if an exception is thrown.

On way to make sure this is done is the using statement (not to be confused with using declaration!):
https://msdn.microsoft.com/en-us/library/aa664736%28v=vs.71%29.aspx[^].
https://msdn.microsoft.com/en-us/library/yh598w02.aspx[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900