一个垃圾收集问题
msdn在讲gchandle时举了这个例子public delegate bool CallBack(int handle, IntPtr param);
public class LibWrap
{
// passing managed object as LPARAM
// BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam);
[DllImport("user32.dll")]
public static extern bool EnumWindows(CallBack cb, IntPtr param);
}
public class App
{
public static void Main()
{
Run();
}
[SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)]
public static void Run()
{
TextWriter tw = System.Console.Out;
GCHandle gch = GCHandle.Alloc(tw);
CallBack cewp = new CallBack(CaptureEnumWindowsProc);
// platform invoke will prevent delegate to be garbage collected
// before call ends
LibWrap.EnumWindows(cewp, GCHandle.ToIntPtr(gch));
gch.Free();
}
private static bool CaptureEnumWindowsProc(int handle, IntPtr param)
{
GCHandle gch = GCHandle.FromIntPtr(param);
TextWriter tw = (TextWriter)gch.Target;
tw.WriteLine(handle);
return true;
}
}
不明白的是,在Run()中,就算不用gchandle,也不至于导致垃圾回收吧?这里我理解gchandle纯粹就是一个数据类似转换了,请高手来讲讲,
另外,就假设需要使用gchandle ,这里gchandle用的是normal类型,不是pinned类型,请问这两种有什么具体体别,最好能举例说明 --------------------编程问答-------------------- 自己顶
补充:.NET技术 , C#