C#异常之约束执行区域(CER)

今天使用了RuntimeHelpers.PrepareConstrainedRegions()方法放在try块之前,然后用ReliabilityContract特性标记了一个方法,在执行try块之前CRL会对catch块和finally做JIT编译,如果在方法中发生了异常,则程序在进入try块之前就会把异常抛出来,这样可以避免类的状态发生改变,如果发生错误不能恢复.具体代码如下

private static void Demo2()
{
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Console.WriteLine("123");
throw new ArgumentNullException();
}
catch
{
testcatch.Mothod1();
}
}

public class testcatch
{
static testcatch()
{
throw new OutOfMemoryException();
}
[ReliabilityContract(Consistency.WillNotCorruptState,Cer.Success)]
public static void Mothod1() { Console.WriteLine("test"); }
}

程序执行时不会输出123.

原文地址:https://www.cnblogs.com/weichao975/p/2781001.html