3

I'm subscribing to a WMI event and receiving a "COM object that has been separated from its underlying RCW cannot be used" error when my application closes. This question has been asked before, but it is quite different from my circumstances.

I am calling this code from my main thread:

string strComputer = @".";
ManagementScope scope = new ManagementScope(@"\\" + strComputer + @"\root\wmi");
scope.Connect();

EventQuery query = new EventQuery("Select * from MSNdis_StatusMediaDisconnect");

ManagementEventWatcher watcher = new ManagementEventWatcher(scope, query);

watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); // some function that does stuff when the event occurs.
watcher.Start();

The event is reported correctly. I suspect the problem is related to the way these objects are deallocated when my application closes. How do I prevent the error? Should I explicitly Dispose of the watcher, scope and query before my application closes?

Community
  • 1
  • 1
Petrus Theron
  • 27,855
  • 36
  • 153
  • 287
  • 1
    Extremely old question, but since this is the first hit on COM RCW I would like to add that this often happens when you close a window before disposing of certain COM objects (as they depend implicitly on the Window handle). Adding some clean-up code in the `Window.OnClosing` event can solve this problem. – Roy T. Feb 11 '15 at 15:49

1 Answers1

4

Well, WMI is COM enabled, the exception is not entirely mysterious. I suspect a race in the finalizer, try fixing it by calling the watcher's Stop() method before you let your program terminate.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • First I overrode Dispose and tried to stop the watcher there, but the error happens before then, so after explicitly stopping the watcher, the error is solved! Thanks Hans! – Petrus Theron Oct 17 '10 at 15:45