如何在GUI线程中捕获异常? [英] How do I catch an exception in a GUI thread?

查看:303
本文介绍了如何在GUI线程中捕获异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于图片框的用户控件中引发了异常,导致该异常显示典型的错误图像(红色X).由于GUI线程本身捕获并处理了异常,因此我无法轻松找出异常发生的位置并进行调试.

An exception is thrown in a user control based on a picture box, causing it to show the typical error image (red X). Since the GUI thread caught and handled the exception itself, I cannot easily find out where the exception occurred and debug.

我目前正在将整个OnPaint代码包装在try-catch中,并且能够调试该代码,但是我发现它非常乏味,因此我想知道是否有办法从GUI线程异常中闯入调试器.

I'm currently wrapping the whole OnPaint code in a try-catch, and was able to debug the code, but I found it quite tedious so I wondered if there is a way to break into debugger from a GUI thread exception.

推荐答案

默认情况下,它已经可以通过这种方式工作. UI线程异常处理方法由Application.SetUnhandledExceptionMode()控制.默认值为UnhandledExceptionMode.CatchException,以便引发ThreadException事件,并默认创建一个ThreadExceptionDialog.

It already works this way by default. The UI thread exception handling method is controlled by Application.SetUnhandledExceptionMode(). The default is UnhandledExceptionMode.CatchException so that the ThreadException event is raised and, by default, creates a ThreadExceptionDialog.

但是,如果连接了调试器,则它将覆盖此模式.因此,如果没有活动的catch子句,将始终无法处理异常.这样调试器将停止运行,从而可以诊断问题.通过编写自己的try/catch,可以防止此操作起作用.

However, if a debugger is attached then it overrides this mode. So that an exception will always be unhandled if there is no active catch clause. So that the debugger will stop, allowing you to diagnose the problem. By writing your own try/catch, you prevent this from working.

请注意OnPaint()可能很特殊,尤其是对于PictureBox.它具有try/catch子句,捕获未处理的异常并绘制红叉.这有点不寻常,但有必要,因为它支持ImageLocation属性.这样就可以显示来自潜在不可靠网络源的图像.在这种情况下,对异常进行故障排除的最佳方法是使用调试+异常",勾选抛出"复选框.这会迫使调试器始终在异常发生时停止,即使该异常未得到处理也是如此.

Do beware that OnPaint() can be special, particularly for PictureBox. It has a try/catch clause, catching an unhandled exception and painting a red cross. This is a bit unusual but necessary because it supports the ImageLocation property. Which lets it display images from a potentially unreliable network source. The best way to trouble-shoot exceptions in that case is with Debug + Exceptions, tick the Thrown checkbox. This forces the debugger to always stop on an exception, even if it isn't unhandled.

这篇关于如何在GUI线程中捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆