《Advanced .NET Debugging》 读书笔记 Listing 5-6: Pining的简单示例
时间:2011-01-06 来源:李志鹏
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace Advanced.NET.Debugging.Chapter5
{
class Pinning
{
static void Main(string[] args)
{
Pinning p = new Pinning();
p.Run();
}
public void Run()
{
SByte[] b1 = null;
SByte[] b2 = null;
SByte[] b3 = null;
Console.WriteLine("Press any key to alloc");
Console.ReadKey();
b1 = new SByte[100];
b2 = new SByte[200];
b3 = new SByte[300];
GCHandle h1 = GCHandle.Alloc(b1, GCHandleType.Pinned);
GCHandle h2 = GCHandle.Alloc(b2, GCHandleType.Pinned);
GCHandle h3 = GCHandle.Alloc(b3, GCHandleType.Pinned);
Console.WriteLine("Press any key to GC");
Console.ReadKey();
GC.Collect();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
h1.Free(); h2.Free(); h3.Free();
}
}
}
程序主要是为是为三个数组指定了Pinned类型的handle。对象一旦被标记了Pinned类型的Handle,那么GC将不能将其回收,且位置也不能移动。可以通过如下方法查看:
1. WinDbg载入 05Pinnings.exe
2. 在handle已经分配以后,执行 !GCHandles ,结果如下:
3. 执行 !Objsize 结果如下:
此时可见是那个SByte数组都有Pinned类型的handle。