C# ManagementScope loses connection and causes memory leaks
I'm using WMI for monitoring all our servers through a small C# service, which creates a bunch of ManagementScopes (one per server it should monitor) and periodically polls for CPU load etc.
However every once in a while it starts throwing COMExceptions, with the message "The RPC server is unavailable". Now that's fair enough if it was true, however I can manully connect to the server just fine, and if I create a new ManagementScope to the same server, I can reconnect without problems!
There's a problem with this approach though: It leaks memory :-(
ManagementScope has no Close, Dispose or similar cleanup function, and leaks memory when just garbage collected. This is, according to all my google searches, a problem with the underlying WMI components, and as such not a .Net issue.
So I figure my best approach is to solve the COMException issue, and just staying with the original ManagementScope - however if I manually call Connect on the scope after the COMException, it does return true (as in "Yes I've got a connection), but at first attempt at getting data from it, it throws another COMException.
I've tried quite a few things, but I simply cannot figure out why this happens :-(
The code is quite large, therefore I haven't pasted it here (and it's split into a lot of classes)
But basically I create a scope, and then call the following methods:
public ManagementObject GetSingleObject(string query)
{
using (var searcher = CreateSearcher(query))
{
try
{
using (var collection = searcher.Get())
{
return collection
.Cast<ManagementObject>()
.FirstOrDefault();
}
}
catch
{
return null;
}
}
}
private Mana开发者_开发知识库gementObjectSearcher CreateSearcher(string query)
{
return new ManagementObjectSearcher(_scope, new ObjectQuery(query), _options);
}
If you need more code, let me know :-)
精彩评论