hello,
i have a view model that is used as the data source for my custom control. in the view model's constructor i set up a WMI ManagementEventWatcher and start it. my view model implements IDisposable, so i stop the watcher in the Dispose method.
when i embed the custom control into a window, and then close the window to exit the application it throws an InvalidComObjectException saying "COM object that has been separated from its underlying RCW cannot be used". this happens because of my watcher, and if i do not create it, there is no exception. there is no additional information about the exception such as stack trace, etc.
my guess is that something keeps the view model until the thread that the watcher uses terminates but before the watcher is stopped. and i do not know how to handle this.
any advice? thanks konstantin
public abstract class ViewModelBase : IDisposable, ...
{
...
protected virtual void OnDispose() { }
void IDisposable.Dispose()
{
this.OnDispose();
}
}
public class DirectorySelector : ViewModelBase
{
private ManagementEventWatcher watcher;
private void OnWMIEvent(object sender, EventArrivedEventArgs e)
{
...
}
protected override void OnDispose()
{
if (this.watcher != null)
{
this.watcher.Stop();
this.watcher = null;
}
base.OnDispose();
}
public DirectorySelector()
{
try
{
this.watcher = new ManagementEventWatcher(new WqlEventQuery(...));
this.watcher.EventArrived += new EventArrivedEventHandler(this.OnWMIEvent);
this.watcher.Start();
}
catch (ManagementException)
{
this.watcher = null;
}
}
}