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?