如何在.NET 4中模拟损坏的状态异常?

时间:2010-06-01 13:28:31

标签: .net state simulation corrupt

好吧,在.NET 4中,Microsoft添加了HandleProcessCorruptedStateExceptions属性:

HandleProcessCorruptedStateExceptionsAttribute Class

我想测试这个功能。如何将我的申请带到“腐败状态”?

3 个答案:

答案 0 :(得分:14)

搞砸垃圾收集堆总是一个好方法:

using System;
using System.Runtime.InteropServices;


class Program {
  unsafe static void Main(string[] args) {
    var obj = new byte[1];
    var pin = GCHandle.Alloc(obj, GCHandleType.Pinned);
    byte* p = (byte*)pin.AddrOfPinnedObject();
    for (int ix = 0; ix < 256; ++ix) *p-- = 0;
    GC.Collect();   // kaboom
  }
}

答案 1 :(得分:13)

只需取消引用随机数:

    private static unsafe void AccessViolation()
    {
        byte b = *(byte*) (8762765876);
    }

或溢出堆栈:

    private static void StackOverflow()
    {
        StackOverflow();
    }

答案 2 :(得分:0)

测试HandleProcessCorruptedStateExceptions功能:

using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
...

[HandleProcessCorruptedStateExceptions]
public void HandleCorruptedStateException()
{
    try
    {
        var ptr = new IntPtr(42);
        Marshal.StructureToPtr(42, ptr, true);
    }
    catch(Exception ex)
    {
         Debug.WriteLine(ex.Message);
    }
}