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!
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 formIDisposable
interface and unregister there. Note thatDispose
method will not be automatically* called like destructor is. You need to determine the place in your code that you think yourmainform
is no longer relevant and call it there. If it is aWindow
derived class then you might try removing your handler inOnClose
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.