除非应用了[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
,否则任何人都可以创建一个会中断的简短示例吗?
我只是浏览了这个sample on MSDN,即使我注释掉ReliabilityContract属性,也无法打破它。终于似乎总是被打来。
最佳答案
using System;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
class Program {
static bool cerWorked;
static void Main( string[] args ) {
try {
cerWorked = true;
MyFn();
}
catch( OutOfMemoryException ) {
Console.WriteLine( cerWorked );
}
Console.ReadLine();
}
unsafe struct Big {
public fixed byte Bytes[int.MaxValue];
}
//results depends on the existance of this attribute
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
unsafe static void StackOverflow() {
Big big;
big.Bytes[ int.MaxValue - 1 ] = 1;
}
static void MyFn() {
RuntimeHelpers.PrepareConstrainedRegions();
try {
cerWorked = false;
}
finally {
StackOverflow();
}
}
}
当MyFn被jitted时,它将尝试从finally块创建一个ConstrainedRegion。