If I am using a ManagementObjectSearcher, I can easily wrap it in a using block:
using (var searcher = new ManagementObjectSearcher(scope, query))
{
// ...
}
It is also easy to dispose the collection returned from the searcher, due to the fact that foreach automatically calls dispose on the enumerator:
using (var searcher = new ManagementObjectSearcher(scope, query))
{
foreach(ManagementObject mo in searcher.Get())
{
// ...
}
}
But ManagementObject also implements IDisposable:
using (var searcher = new ManagementObjectSearcher(scope, query))
{
foreach(ManagementObject mo in searcher.Get())
{
// ...
mo.Dispose(); // ?
}
}
- Do I have to dispose each
ManagementObjectinstance returned in this scenario? - If I do, how do I make it exception safe?
- Is there a way I can still use Linq in this scenario (and still properly call
Dispose)? Especially with constructions likesearcher.Get().First()?
Edit: A few more related questions:
- Do I also have to call
Disposeon the search result collection? - How about the searcher?
They both also implement their own IDisposable method, though it seems like the searcher only inherits the Dispose implementation from Component; it doesn’t add its own dispose behavior.
ManagementObjectinherits fromSystem.ComponentModel.Componentand you should callDisposeexplicitly for all inherited fromComponentobjects.You can use
LINQmethods with your own predicates which invokesDisposeitself:This code is equivalent to:
Where
Satisfyis your own method.