Reputation: 63
I have doubts about releasing IDisposable objects.
using (ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT * FROM Win32_Service"))
{
using (ManagementObject item = s.Get().Cast<ManagementObject>().Last())
{
}
}
Should I also put collection from s.Get() into using?
using (ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT * FROM Win32_Service"))
{
using (ManagementObjectCollection items = s.Get())
{
using (ManagementObject item = items.Cast<ManagementObject>().Last())
{
}
}
}
Does linq dispose collection (s.Get()) from my first block of code in this topic?
s.Get().Cast<ManagementObject>().Last()
Upvotes: 1
Views: 2630
Reputation: 7824
If you look at the documentation for using
Multiple objects can be used in with a using statement, but they must be declared inside the using statement
So I would expect those two sets of using blocks to be equivalent. However, while ManagementObjectCollection implements IDisposable ManagementObject does not and the documentation for using also tells us:
The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
So, since the using block can't dispose of the ManagementObject resources anyway, you don't need ManagementObject in its own using block and can use
using (ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT * FROM Win32_Service"))
{
using (ManagementObjectCollection items = s.Get())
{
ManagementObject item = items.Cast<ManagementObject>().Last();
//do stuff
}
}
To be honest since items
and item
are scoped within the using block you probably only need
using (ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT * FROM Win32_Service"))
{
ManagementObjectCollection items = s.Get()
ManagementObject item = items.Cast<ManagementObject>().Last();
//do stuff
}
That should free them for GarbageCollection so while you don't know that items
has its Dispose method called at the end of the using block it will be called on the next collection.
Upvotes: 1