Unregister Message in Destructor make error ({“Han

2019-08-11 23:08发布

Is there anyone who experienced the same error like me: Situation: - I'm using MVVMLight v4 with my window application: - I have a windows form : such as mainform - In code-behind class (mainform.xaml.cs), I have a constructor & a deconstructor:

public mainform()
{
    Messenger.Default.Register<NotificationMessage>(
        this,
        msg =>
        {
           //// Do something
        }
}

~mainform()
{
    Messenger.Default.Unregister<NotificationMessage>(this);
}

Those code run well, but when the form is closed, an exception will be thrown: System.InvalidOperationException {"Handle is not initialized."} Stacktrace:

   at System.WeakReference.set_Target(Object value)
   at System.Windows.Threading.Dispatcher.FromThread(Thread thread)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.IntDestroyWindow(HandleRef hWnd)
   at MS.Win32.HwndWrapper.DestroyWindow(Object args)
   at MS.Win32.HwndWrapper.Dispose(Boolean disposing, Boolean isHwndBeingDestroyed)
   at MS.Win32.HwndWrapper.Finalize()

When I remove the deconstructor, no exception is thrown. & when the exception thrown, my visual studio is also crashed -> restart.

I seek out some quite similar question, but without clear answer. Is there any advice for me?

Thanks all!

1条回答
三岁会撩人
2楼-- · 2019-08-11 23:21

Destructors are EVIL.

Seriously you should NOT use destructors in C# if you are not releasing some unmanaged resources (which is very very rare). The way to go in your scenario is to introduce or override Dispose method form IDisposable interface and unregister there. Note that Dispose method will not be automatically* called like destructor is. You need to determine the place in your code that you think your mainform is no longer relevant and call it there. If it is a Window derived class then you might try removing your handler in OnClose event.

On the other hand if this is really a main window that is closed and then application is closed then why bother.

*as noted by Dtex MVVMLight might just do that.

查看更多
登录 后发表回答