【问题标题】:Why PrepareConstrainedRegions method does not work in c#?为什么 PrepareConstrainedRegions 方法在 c# 中不起作用?
【发布时间】:2020-10-02 04:50:43
【问题描述】:

我阅读了 Jeffrey Richter 的“CLR via C#”一书。在第 20 章中,有一个代码示例演示了约束执行区域 (CER) 的用法:

private static void Demo2() {
 // Force the code in the finally to be eagerly prepared
 RuntimeHelpers.PrepareConstrainedRegions(); // System.Runtime.CompilerServices namespace
 try {
 Console.WriteLine("In try");
 }
 finally {
 // Type2’s static constructor is implicitly called in here
 Type2.M();
 }
}
public class Type2 {
 static Type2() {
 Console.WriteLine("Type2's static ctor called");
 }
 // Use this attribute defined in the System.Runtime.ConstrainedExecution namespace
 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
 public static void M() { }
}

还有以下文字:

现在,当我运行这个版本的代码时,我会得到以下输出。

Type2's static ctor called
In try

但是当我运行这段代码时,无论我是否使用 CER,我都会得到以下输出:

In try
Type2's static ctor called

所以,Type2 构造函数在try 块之后被调用(据我了解,这违反了 CER 用法的含义)。

这可能是什么原因?

编辑: 我正在使用 .Net Core 3.1 和 VS Enterprise 2019 Preview 16.6.0预览版3.0,我的代码是:

using System;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;

public sealed class Program
{
    public static void Main()
    {
        Demo2();
    }
    private static void Demo2()
    {
        RuntimeHelpers.PrepareConstrainedRegions();
        try
        {
            Console.WriteLine("In try");
        }
        finally
        {
            Type2.M();
        }
    }
}
public class Type2
{
    static Type2()
    {
        Console.WriteLine("Type2's static ctor called");
    }
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    public static void M() { }
}

顺便说一下,Type2 类可以在Program 里面,它不会改变输出。

【问题讨论】:

  • 你能显示相关的,你在哪里调用方法
  • FWIW,它适用于我的(.NET Fx 4.6.2、4.7.2 和 .NET Core 3.1)。顺便说一句,您的代码不可编译。它缺少using 指令。您可能需要指出您使用的是哪个 .NET 版本。
  • 和你一样,我正在使用 .Net Core 3.1
  • @helgez,我在 .NET Core3.1、.NET Core3.0、.NET Core2.1、.NET Core2.0 上测试您的代码,PrepareConstrainedRegions() 不起作用,并且在.NET Core2.2,出现其他错误,但在 .NET Framework4.7.2、.NET Framework4.6.1 中,PrepareConstrainedRegions() 有效。我觉得是平台问题。你可以试试 .net framework 来测试代码。

标签: c# visual-studio clr cer constrained-execution-reg


【解决方案1】:

(这不是这里实际情况的完整答案,但它可能会对您有所帮助)

您的问题很可能是您在 Visual Studio 中运行进程(使用 CTRL+F5)。然后通过VsDebugConsole.exe 启动它,然后启动您的进程(另见this)。

无论出于何种原因 - 这需要进行研究 - 它看起来以这种方式运行时好像没有兑现 CER。

您可以做的验证是尝试直接从命令提示符/控制台运行您的程序。

【讨论】:

  • 是的,我已经尝试使用 csc.exe 编译我的代码,并且它应该可以正常工作。但是,在 VS 中,我选择“发布”,在不调试的情况下启动应用程序(ctrl + f5),并且(出于某种原因,即使我什至无法通过断点等进行调试)它只是没有显示我的正常行为。我认为 VS 中应该有一些其他设置/选项可以使这个(也许还有其他的?)起作用,但我不知道在哪里可以找到它。 P.S 从答案到链接帖子的设置没有帮助。
【解决方案2】:

这里引用了微软关于Constrained Execution Regions的文章:

CER 仅在 .NET Framework 中受支持。本文不适用于 .NET Core 或 .NET 5 及更高版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 2019-07-18
    • 2011-03-04
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多