1

我读了 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被调用(打破了 CER 用法的含义,据我所知)。 try

这可能是什么原因?

编辑: 我正在使用 .Net Core 3.1 和 VS Enterprise 2019 Preview Version 16.6.0 Preview 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,它不会改变输出。

4

2 回答 2

0

(This is not the full answer to what is actually going on here, but it might help you)

Your problem is most likely that you run your process from within Visual Studio (using CTRL+F5). It is then launched via VsDebugConsole.exe, which then starts your process (also see this).

For whatever reason - that would need to be researched - it looks as if CERs are not honored when running in this way.

What you could do to validate, is attempt to run your program directly from the command prompt / console.

于 2020-06-14T09:19:33.993 回答
0

这是微软关于约束执行区域的文章的引用:

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

于 2021-02-21T18:21:48.290 回答