如何获得线程异常来仅终止当前命令或 WinForms 应用程序?
我的 .NET Windows 窗体应用程序有各种命令调用我的命令函数,这些函数可以抛出由我的处理程序在 Application.ThreadException 处处理的异常。我希望这个处理程序能够终止命令函数而不终止应用程序,即使在命令函数没有 try/catch 的情况下也是如此。获得这个的最好方法是什么?
谢谢。
My .NET Windows Forms app has various commands calling my command functions that can throw exceptions handled by my handler at Application.ThreadException. I would like this handler to terminate the command function without terminating the app, even in the case of a command function that has no try/catch. What's the best way to get this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一个建议是使用
Task
类(因为它支持取消)Another suggestion is to use a
Task
class (as it supports Cancelation)最简单的方法是将每个“命令”包装在自己的 try/catch 块中,您可以以相当通用的方式执行此操作。只需在异常进入消息循环之前捕获该异常即可。因此,如果您之前:
您会:
然而,值得注意的是,捕获所有异常通常不是一个好主意。如果可以的话,捕获非常具体的异常。
The simplest approach would be to wrap each of your "commands" in its own try/catch block, which you can do in a fairly generic way. Just catch the exception before it hits the message loop. So if before you had:
you'd have:
It's worth noting, however, that catching all exceptions isn't usually a good idea. If you can, catch very specific exceptions instead.