WMI Exception: “COM object that has been separated

2019-07-07 04:28发布

问题:

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?

回答1:

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.