开发者

how to cleanup view model properly?

开发者 https://www.devze.com 2023-01-17 03:39 出处:网络
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 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();
        }
 开发者_如何学C       catch (ManagementException)
        {
            this.watcher = null;
        }
    }
}


this article has the solution: Disposing WPF User Controls

basically, WPF dos not seem to use IDisposable anywhere, so the app needs to cleanup itself explicitly. so in my case, i subscribe to the Dispatcher.ShutdownStarted event from my control that uses the view model that needs to be disposed, and dispose the control's DataContext from the event handler.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号