tags:

views:

25

answers:

1

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?

+2  A: 

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
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!
FreshCode