.NET的GCHandler

简介:

我们在使用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 
= 0,
          CTRL_BREAK_EVENT,
          CTRL_CLOSE_EVENT,
          CTRL_LOGOFF_EVENT 
= 5,
          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(
10000);
  
          
// 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();
      }
  }




  本文转自loose_went博客园博客,原文链接:http://www.cnblogs.com/michaelxu/archive/2010/05/19/1739158.html,如需转载请自行联系原作者

相关文章
qnx下手动修改时间指令
qnx下手动修改时间指令
605 0
|
消息中间件 物联网 网络性能优化
MQTT常见问题之mqtt 连接一直显示 Not authorized to connect如何解决
MQTT(Message Queuing Telemetry Transport)是一个轻量级的、基于发布/订阅模式的消息协议,广泛用于物联网(IoT)中设备间的通信。以下是MQTT使用过程中可能遇到的一些常见问题及其答案的汇总:
|
6月前
|
前端开发 Java 数据库连接
java bo 对象详解_全面解析 java 中 PO,VO,DAO,BO,POJO 及 DTO 等几种对象类型
Java开发中常见的六大对象模型(PO、VO、DAO、BO、POJO、DTO)各有侧重,共同构建企业级应用架构。PO对应数据库表结构,VO专为前端展示设计,DAO封装数据访问逻辑,BO处理业务逻辑,POJO是简单的Java对象,DTO用于层间数据传输。它们在三层架构中协作:表现层使用VO,业务层通过BO调用DAO处理PO,DTO作为数据传输媒介。通过在线商城的用户管理模块示例,展示了各对象的具体应用。最佳实践包括保持分层清晰、使用工具类转换对象,并避免过度设计带来的类膨胀。理解这些对象模型的区别与联系。
413 1
|
监控 Ubuntu 数据可视化
如何使用各种工具和命令来检查 Ubuntu 中的 CPU 使用情况?
如何使用各种工具和命令来检查 Ubuntu 中的 CPU 使用情况?
3982 0
如何使用各种工具和命令来检查 Ubuntu 中的 CPU 使用情况?
解决win11开启移动热点共享手机连上后无法上网的问题
本文提供了解决Windows 11开启移动热点后手机无法上网问题的步骤:通过控制面板进入网络和共享中心,在以太网属性中勾选“允许其他网络用户通过此计算机的Internet连接来连接”,然后手机重新连接共享热点即可上网。
|
编解码 Android开发
selinux报avc denied权限和编译报neverallow 解决方案
selinux报avc denied权限和编译报neverallow 解决方案
1592 1
|
JavaScript 程序员 开发者
美哭了,一款面向程序员的 Markdown 笔记应用
今天给大家推荐一个开源的面向程序员的本地系统 Markdown 笔记工具。一款适合程序员的笔记工具,拥有和其它工具不一样的体验
|
关系型数据库 MySQL 数据库
提取日期信息:解析MySQL中的DATE()函数
在数据库管理中,从日期时间值中提取日期部分是非常常见的操作,而DATE()函数正是用于帮助我们实现这一目标的工具。
694 0
JM
|
算法 数据可视化 C++
修改 UE5 中的渲染管线
前言本文重点介绍如何修改 UE5 中的渲染管线,要修改渲染管线有一些前置知识需要理解,因此笔者会先简单介绍下渲染管线的概念以及当前主流的渲染管线的实现思路,为后面在 UE5 中自定义渲染管线做铺垫;要注意本文默认渲染管线即是光栅化渲染管线(不考虑光线追踪),同时也不会介绍太多管线的实现细节和当下流行的优化版本,对渲染管线实现细节感兴趣的可以自行查阅相关资料。渲染管线 Rendering Pipel
JM
4072 0
修改 UE5 中的渲染管线
|
IDE Java 应用服务中间件
Tomcat远程Debug
JVM本身提供可调试运行在虚拟机中的代码的功能。远程调试大致流程为: 1. 在启动的时候设置启动参数以开启和配置调试功能 2. 设置ip白名单或者关闭防火墙,让远端可以访问JVM所在机器 3. IDE中配置远程调试信息 4. 重启Tomcat,在IDE中启动远端调试
718 0