在析构函数中取消注册消息会导致错误({“未初始化句柄."}) [英] Unregister Message in Destructor make error ({"Handle is not initialized."})
问题描述
有没有人遇到过和我一样的错误: 情况: -我在窗口应用程序中使用了MVVMLight v4: -我有一个Windows窗体:例如mainform -在代码隐藏类(mainform.xaml.cs)中,我有一个构造函数&解构函数:
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);
}
那些代码运行良好,但是当表单关闭时,将引发异常: System.InvalidOperationException {句柄未初始化."} 堆栈跟踪:
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?
谢谢!
推荐答案
析构函数是EVIL.
Destructors are EVIL.
严重的是,如果您不释放一些非托管资源(这非常罕见),则不应在C#中使用析构函数.在您的方案中进行操作的方法是引入或覆盖IDisposable
接口形式的Dispose
方法,然后在此处注销.请注意,不会自动*调用Dispose
方法,就像析构函数一样.您需要确定代码中您认为mainform
不再相关的位置,然后在此位置进行调用.如果它是Window
派生的类,则您可以尝试在OnClose
事件中删除处理程序.
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.
*如Dtex MVVMLight所指出的那样.
*as noted by Dtex MVVMLight might just do that.
这篇关于在析构函数中取消注册消息会导致错误({“未初始化句柄."})的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!