Unregister Message in Destructor make error ({“Handle is not initialized.”})

浪子不回头ぞ 提交于 2019-12-11 13:44:00

问题


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:


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.



来源:https://stackoverflow.com/questions/13912718/unregister-message-in-destructor-make-error-handle-is-not-initialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!