偶数处理程序代码块中未处理的异常
我正在用 C++/CLI 编写一个 DLL,该 DLL 在基于 C# 的 GUI 应用程序中调用。我抛出一个自定义异常(从 Exception 类派生),如果该异常没有被吞入我的 DLL 中,则会在 GUI 代码中的最终 catch 块中进行处理。它适用于所有抛出,除了一个:
我的 DLL 我已经实现了一个处理程序,它将侦听 SerialPort::DataReceived 事件。如果我收到不正确的数据包,我会引发一个自定义异常,该异常会在最外层的 try-catch 块中重新抛出。 GUI 应该显示此自定义异常。但由于某种原因,该块中引发的异常不会重新引发。相反,我在调试模式下收到“未处理的异常”消息。当我通过双击 exe(在发布文件夹中)直接运行 exe 时,它会崩溃。显然,GUI 不处理此事件处理程序方法中引发的异常。或者也许它们没有从我的 DLL 传递到 GUI。它不会给我的 dll 的其他部分带来问题。我认为这种不同行为的唯一原因是事件处理程序没有调用者。我的猜测正确吗?还是有其他原因。关于我如何处理这个问题的任何线索?我不希望我的应用程序崩溃。我只是想引发一个异常,以便可以在 GUI 中向用户显示消息,并且应用程序可以停止与串行端口通信。
I am coding a DLL in C++/CLI that is called in a C# based GUI application. I throw a custom exception (derived from Exception class), which, if not swallowed in my DLL, is handled in the final catch block in the GUI code. It works well for all throws, save one:
Im my DLL I have implemented a handler that will listen to SerialPort::DataReceived events. If I get an incorrect packet, I raise a custom exception, which is rethrown in the outermosst try-catch block. The GUI is supposed to display this custom exception. But for some reason an exception raised in this block is not re-thrown. Instead I get an "Unhandled exception" message in Debug mode. When I run the exe directly by double clicking the exe (in release folder) it simply crashes. Apparently, exceptions raised in this event handler method are not handled by the GUI. Or maybe they are not passed to the GUI from my DLL. It doesnt create a problem for other parts of my dll. The only reason I can think for this different behaviour is that the event handler doesn't have a caller. Is my guess correct? or is there some other reason. Any clues on how I can handle this problem? I dont want my application to crash. I just want to raise an exception so that the message can be displayed to the user in the GUI and the application can stop communicating with the serial port.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在从该事件处理程序抛出之前,您需要切换到 UI 线程。这通常是通过 System::Threading::SynchronizationContext,但如果您使用的是 WinForms,您也可以使用 System::Windows::Forms::Control::BeginInvoke 或 System::Windows::Forms::Control::Invoke。
You need to switch to the UI thread before throwing from that event handler. This is typically accomplished with System::Threading::SynchronizationContext, but if you're using WinForms you can alternatively use System::Windows::Forms::Control::BeginInvoke or System::Windows::Forms::Control::Invoke.