当线程遇到未处理的异常时 CLR 退出
我的应用程序中有后台线程。当其中一个线程发生未处理的异常时,整个 CLR 都会退出。
这是正常行为,还是 CLR 中的错误?
我希望线程将退出,但 CLR 将继续工作。
I have background threads in my application. When one of the threads gets an exception that is not handled the entire CLR exits.
Is it normal behavior, or is it a bug in the CLR?
I would expect that the thread will exit but the CLR will continue working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
.NET 应用程序中的默认行为是在发生未处理的异常时退出。当异常未处理时,程序处于未知且可能不稳定的状态。仅仅因为它发生在后台线程中并不意味着该错误不会影响程序的其余部分。在这种情况下,运行时最谨慎的做法是转储程序。
您可能会研究
AppDomain.CurrentDomain.UnhandledException
,这将允许您捕获未处理的异常并做出相应的反应。更好的解决方案是用try...catch
包装线程过程。但只能让它处理它知道如何处理的异常。这样做:这是一个非常糟糕的主意,因为它可以掩盖您确实希望传播到主程序的异常。
The default behavior in .NET applications is to exit whenever an unhandled exception occurs. When an exception goes unhandled, the program is in an unknown and possibly unsteady state. Just because it happened in a background thread doesn't mean that the error won't affect the rest of the program. The most prudent course for the runtime in that situation is to dump the program.
You might look into
AppDomain.CurrentDomain.UnhandledException
, which will allow you to catch unhandled exceptions and react accordingly. A better solution is to wrap your thread proc with atry...catch
. But only have it handle those exceptions it knows how to handle. Doing this:Is a really bad idea, because it can mask exceptions that you really do want to be propagated to the main program.
您预期的行为曾经是 1.1 中的行为。人们普遍认为这是一个坏主意。当任何线程中存在未处理的异常时,您的进程可能会处于不一致的状态。对共享数据的更新可能会部分应用,等等。运行时没有安全处理这种情况的信息,甚至不知道你想如何处理这种情况,所以它的选择相当于终止线程并让你的程序继续运行。一种奇怪的状态。这可能会导致资源泄漏、挂起、数据损坏等。通过在出现未处理异常的情况下终止进程,您可以确切地知道发生了什么,进程就会结束。
Your expected behavior used to be the behavior back in 1.1. It was generally considered to have been a bad idea. When you have an unhandled exception in any thread, your process can be left in an inconsistent state. Updates to shared data may be partially applied, etc. The runtime doesn't have the information to safely handle this scenario, or even know how you want to handle this scenario, so its choice would amount to terminating the thread and leaving your program in a strange state. This could lead to resource leaks, hangs, corruption of data, etc. By terminating the process given an unhandled exception you know exactly what happens, the process ends.
这是 v2.0 以来 CLR 的正常行为。这是关于此的 MSDN 帖子。为了避免进程终止,您可以使用类似的方法,
但这是不可取的。
This is a normal behavior of the CLR from v2.0. Here is a MSDN post on this. To avoid process from terminating you could use something like this
which is not advisable.
这是正常行为。也许您想捕获异常以防止应用程序退出。
It is normal behavior. Perhaps you want to catch the exception to prevent the application from exiting.