gpt4 book ai didi

c# - CLR 中的错​​误? CLR 执行引擎失败

转载 作者:行者123 更新时间:2023-11-30 14:13:09 35 4
gpt4 key购买 nike

AFAIK,tryfinally block 用于执行一段可能会抛出一些异常的代码,我们还添加了 catch block ,如果我们准备处理某种类型的异常和/或将它们排除在外,比如 FileIOExceptionAccessRight 或其他。但是当我运行它时..

private void button1_Click(object sender, EventArgs e)
{
try
{
Environment.FailFast("It failed");
}
finally
{
MessageBox.Show("Done");
}
}

它异常中断并说

检测到致命执行引擎错误
消息:运行时遇到 fatal error 。错误地址位于线程 0xd04 上的 0x032526f4。错误代码是 0x80131623。此错误可能是 CLR 中的错​​误,或者是用户代码的不安全或不可验证部分中的错误。此错误的常见来源包括 COM 互操作或 PInvoke 的用户编码错误,这可能会损坏堆栈。

现在msdn

Usually, when an unhandled exception ends an application, whether or not the finally block is run is not important. However, if you have statements in a finally block that must be run even in that situation, one solution is to add a catch block to the try-finally statement.

所以,我添加了 catch block ,但它仍然说同样的事情。

    private void button1_Click(object sender, EventArgs e)
{
try
{
Environment.FailFast("It failed");
}
catch (Exception ex)
{

}
finally
{
MessageBox.Show("Done");
}
}

再次失败,同样的错误。至于 CLR 说 finally 中的代码块总是运行(至少在添加 catch 时),肯定不是这样。评论/意见有人吗?

还有截图..

enter image description here

最佳答案

这是设计使然。 Environment.FailFast 的目的是立即停止执行。按照设计,它不会在 catch 或 finally block 中运行任何代码。

documentation说:

This method terminates a process without running any active try/finally blocks or finalizers.

The FailFast method writes the message string to the Windows Application event log, creates a dump of your application, and then terminates the current process. The messa string is also included in error reporting to Microsoft.

Use the FailFast method instead of the Exit method to terminate your application if the state of your application is damaged beyond repair, and executing your application's try/finally blocks and finalizers will corrupt program resources.

这清楚地表明您的 finally block 中的代码将不会运行。如果有一种方法可以让代码在 Environment.FailFast 之后运行,那么这将使 Environment.FailFast 变得毫无用处。它的存在是基于这样一个事实,即您的代码在您调用它之后不会执行。

您指向的文档指出(强调我的):

Usually, when an unhandled exception ends an application, whether or not the finally block is run is not important. However, if you have statements in a finally block that must be run even in that situation, one solution is to add a catch block to the try-finally statement.

但是这些话在这里根本不适用。您假设当您调用 Environment.FailFast 时,未处理的异常终止了应用程序。事实并非如此。应用程序只是当场终止——没有未处理的异常。

关于c# - CLR 中的错​​误? CLR 执行引擎失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15173774/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com