众所周知,我们在使用c#托管代码时,内存地址和GC回收那不是我们关心的,CLR已经给我们暗箱操作。

但是如果我们在c#中调用了一个非托管代码,比如vc的DLL,而且他有个回调函数,需要引用c#中的某个对象并操作,
这时候你就得要小心了。
要是非托管代码中用到得托管代码那个对象被GC给回收了,这时候就会报内存错误。
所以我们就要把那个对象“钉”住(pin),让它的内存地址固定,而不被垃圾回收掉,然后最后我们自己管理,自己释放内存,这时候就需要GCHandle,来看个msdn上的例子:

 public delegate bool CallBack(int handle, IntPtr param);
public class LibWrap
{
[DllImport("user32.dll")]
public static extern bool EnumWindows(CallBack cb, IntPtr param);
} class Program
{
static void Main(string[] args)
{ TextWriter tw = System.Console.Out;
GCHandle gch = GCHandle.Alloc(tw);
CallBack cewp = new CallBack(CaptureEnumWindowsProc);
LibWrap.EnumWindows(cewp, (IntPtr)gch);
gch.Free();
Console.Read(); }
private static bool CaptureEnumWindowsProc(int handle, IntPtr param)
{
GCHandle gch = (GCHandle)param;
TextWriter tw = (TextWriter)gch.Target; tw.WriteLine(handle);
return true;
} }

对上面的代码,略加解释:gch 会钉住(pin)tw这个对象,使其不受GC管理,告诉它,以后你崩管我,我也不用给你上税,其实管理权已经给gch,通过free来释放内存。
这种情况主要用在托管和非托管代码交互的时候,防止内存泄露来使用GCHandle。

另也可以使用GC.KeepAlive 方法(引用msdn)
KeepAlive 方法的目的是确保对对象的引用存在,该对象有被垃圾回收器过早回收的危险。这种现象可能发生的一种常见情形是,当在托管代码或数据中已没有对该对象的引用,但该对象仍然在非托管代码(如 Win32 API、非托管 DLL 或使用 COM 的方法)中使用。
下面是例子:

using System;
using System.Threading;
using System.Runtime.InteropServices; // A simple class that exposes two static Win32 functions.
// One is a delegate type and the other is an enumerated type.
public class MyWin32
{
// Declare the SetConsoleCtrlHandler function
// as external and receiving a delegate.
[DllImport("Kernel32")]
public static extern Boolean SetConsoleCtrlHandler(HandlerRoutine Handler,
Boolean Add); // A delegate type to be used as the handler routine
// for SetConsoleCtrlHandler.
public delegate Boolean HandlerRoutine(CtrlTypes CtrlType); // An enumerated type for the control messages
// sent to the handler routine.
public enum CtrlTypes
{
CTRL_C_EVENT = ,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = ,
CTRL_SHUTDOWN_EVENT
}
} public class MyApp
{
// A private static handler function in the MyApp class.
static Boolean Handler(MyWin32.CtrlTypes CtrlType)
{
String message = "This message should never be seen!";
// A switch to handle the event type.
switch (CtrlType)
{
case MyWin32.CtrlTypes.CTRL_C_EVENT:
message = "A CTRL_C_EVENT was raised by the user.";
break;
case MyWin32.CtrlTypes.CTRL_BREAK_EVENT:
message = "A CTRL_BREAK_EVENT was raised by the user.";
break;
case MyWin32.CtrlTypes.CTRL_CLOSE_EVENT:
message = "A CTRL_CLOSE_EVENT was raised by the user.";
break;
case MyWin32.CtrlTypes.CTRL_LOGOFF_EVENT:
message = "A CTRL_LOGOFF_EVENT was raised by the user.";
break;
case MyWin32.CtrlTypes.CTRL_SHUTDOWN_EVENT:
message = "A CTRL_SHUTDOWN_EVENT was raised by the user.";
break;
} // Use interop to display a message for the type of event.
Console.WriteLine(message); return true;
} public static void Main()
{ // Use interop to set a console control handler.
MyWin32.HandlerRoutine hr = new MyWin32.HandlerRoutine(Handler);
MyWin32.SetConsoleCtrlHandler(hr, true); // Give the user some time to raise a few events.
Console.WriteLine("Waiting 30 seconds for console ctrl events"); // The object hr is not referred to again.
// The garbage collector can detect that the object has no
// more managed references and might clean it up here while
// the unmanaged SetConsoleCtrlHandler method is still using it. // Force a garbage collection to demonstrate how the hr
// object will be handled.
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect(); Thread.Sleep(); // Display a message to the console when the unmanaged method
// has finished its work.
Console.WriteLine("Finished!"); // Call GC.KeepAlive(hr) at this point to maintain a reference to hr.
// This will prevent the garbage collector from collecting the
// object during the execution of the SetConsoleCtrlHandler method.
GC.KeepAlive(hr);
Console.Read();
}
}

GCHandler的使用的更多相关文章

随机推荐

  1. folder、source folder、package 区别与联系

    在eclipse下,package,source folder,folder都是文件夹.  它们的区别如下:  package:当你在建立一个package时,它自动建立到source folder下 ...

  2. Vs2010在C#类文件头部添加文件注释的方法

    步骤: 1.VS2010 中找到(安装盘符以C盘为例) 32位操作系统路径:C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\Item ...

  3. Java内存模型

    1. 概述 多任务和高并发是衡量一台计算机处理器的能力重要指标之一.一般衡量一个服务器性能的高低好坏,使用每秒事务处理数(Transactions Per Second,TPS)这个指标比较能说明问题 ...

  4. php 面试题收集-基础题

    1.表单中 get与post提交方法的区别?答:get是发送请求HTTP协议通过url参数传递进行接收,而post是实体数据,可以通过表单提交大量信息. 2.session与cookie的区别?答:s ...

  5. PLL输出怎么不能配置成我想要的时钟

    如下图,我的clk_out7想配置成160M,十几输出变为了150M

  6. uiscrollView UINavigation和uitabbar添加约束的问题

    首先是层次问题, 我的storyboard中 底层是一个View(viewcontroller自带)上面添加了一个UIScrollview(添加约束, 上下左右全为0), 在UIScrollview上 ...

  7. golang使用 mongo

    连接集群 mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?op ...

  8. TortoiseGit 连接Git服务器不用每次输入用户名和密码的方法

    每次git push 都要输入用户名和密码. 虽然安全,但在自己电脑上每次都输有些麻烦,如何记住用户名和密码呢? 试了很多方法,找到这个最简单,亲测可行. 当你配置好git后,在C盘C:\Users\ ...

  9. php_html转译符号

    1.双引号 /" 或者 " 2.单引号 ' > 4. & &

  10. Python之路,Day6 - 面向对象学习

    本节内容:   面向对象编程介绍 为什么要用面向对象进行开发? 面向对象的特性:封装.继承.多态 类.方法. 引子 你现在是一家游戏公司的开发人员,现在需要你开发一款叫做<人狗大战>的游戏 ...