【发布时间】: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