title: C# ManagementScope loses connection and causes memory leaks
body: <p>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.</p>
  
  <p>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, <strong>and</strong> if I create a new ManagementScope to the same server, I can reconnect without problems!</p>
  
  <p>There's a problem with this approach though: It leaks memory :-(</p>
  
  <p>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.</p>
  
  <p>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 <strong>does</strong> return true (as in "Yes I've got a connection), but at first attempt at getting data from it, it throws another COMException.</p>
  
  <p>I've tried quite a few things, but I simply cannot figure out why this happens :-(</p>
  
  <p>The code is quite large, therefore I haven't pasted it here (and it's split into a lot of classes)</p>
  
  <p>But basically I create a scope, and then call the following methods:</p>
  
  <pre><code>public ManagementObject GetSingleObject(string query)
  {
      using (var searcher = CreateSearcher(query))
      {
          try
          {
              using (var collection = searcher.Get())
              {
                  return collection
                          .Cast&lt;ManagementObject&gt;()
                          .FirstOrDefault();
              }
          }
          catch
          {
              return null;
          }
      }
  }
  
  private ManagementObjectSearcher CreateSearcher(string query)
  {
      return new ManagementObjectSearcher(_scope, new ObjectQuery(query), _options);
  }
  </code></pre>
  
  <p>If you need more code, let me know :-)</p>