《你不常用的c#之二》:略谈GCHandle

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

[c-sharp]  view plain copy
  1. public delegate bool CallBack(int handle, IntPtr param);  
  2.          public class LibWrap  
  3.          {  
  4.              [DllImport("user32.dll")]  
  5.           public static extern bool EnumWindows(CallBack cb, IntPtr param);  
  6.       }  
  7.     
  8.   class Program  
  9.       {  
  10.           static void Main(string[] args)  
  11.           {  
  12.     
  13.   TextWriter tw = System.Console.Out;  
  14.               GCHandle gch = GCHandle.Alloc(tw);  
  15.               CallBack cewp = new CallBack(CaptureEnumWindowsProc);  
  16.               LibWrap.EnumWindows(cewp, (IntPtr)gch);  
  17.               gch.Free();  
  18.               Console.Read();  
  19.     
  20.   }  
  21.   private static bool CaptureEnumWindowsProc(int handle, IntPtr param)  
  22.           {  
  23.               GCHandle gch = (GCHandle)param;  
  24.               TextWriter tw = (TextWriter)gch.Target;  
  25.     
  26.   tw.WriteLine(handle);  
  27.               return true;  
  28.           }  
  29.     
  30.   }  
 

 

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

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

[c-sharp]  view plain copy
  1. using System;  
  2.   using System.Threading;  
  3.   using System.Runtime.InteropServices;  
  4.     
  5.   // A simple class that exposes two static Win32 functions.  
  6.   // One is a delegate type and the other is an enumerated type.  
  7.   public class MyWin32  
  8.   {  
  9.       // Declare the SetConsoleCtrlHandler function   
  10.       // as external and receiving a delegate.     
  11.       [DllImport("Kernel32")]  
  12.       public static extern Boolean SetConsoleCtrlHandler(HandlerRoutine Handler,  
  13.           Boolean Add);  
  14.     
  15.       // A delegate type to be used as the handler routine   
  16.       // for SetConsoleCtrlHandler.  
  17.       public delegate Boolean HandlerRoutine(CtrlTypes CtrlType);  
  18.     
  19.       // An enumerated type for the control messages   
  20.       // sent to the handler routine.  
  21.       public enum CtrlTypes  
  22.       {  
  23.           CTRL_C_EVENT = 0,  
  24.           CTRL_BREAK_EVENT,  
  25.           CTRL_CLOSE_EVENT,  
  26.           CTRL_LOGOFF_EVENT = 5,  
  27.           CTRL_SHUTDOWN_EVENT  
  28.       }  
  29.   }  
  30.     
  31.   public class MyApp  
  32.   {  
  33.       // A private static handler function in the MyApp class.  
  34.       static Boolean Handler(MyWin32.CtrlTypes CtrlType)  
  35.       {  
  36.           String message = "This message should never be seen!";  
  37.     
  38.           // A switch to handle the event type.  
  39.           switch (CtrlType)  
  40.           {  
  41.               case MyWin32.CtrlTypes.CTRL_C_EVENT:  
  42.                   message = "A CTRL_C_EVENT was raised by the user.";  
  43.                   break;  
  44.               case MyWin32.CtrlTypes.CTRL_BREAK_EVENT:  
  45.                   message = "A CTRL_BREAK_EVENT was raised by the user.";  
  46.                   break;  
  47.               case MyWin32.CtrlTypes.CTRL_CLOSE_EVENT:  
  48.                   message = "A CTRL_CLOSE_EVENT was raised by the user.";  
  49.                   break;  
  50.               case MyWin32.CtrlTypes.CTRL_LOGOFF_EVENT:  
  51.                   message = "A CTRL_LOGOFF_EVENT was raised by the user.";  
  52.                   break;  
  53.               case MyWin32.CtrlTypes.CTRL_SHUTDOWN_EVENT:  
  54.                   message = "A CTRL_SHUTDOWN_EVENT was raised by the user.";  
  55.                   break;  
  56.           }  
  57.     
  58.           // Use interop to display a message for the type of event.  
  59.           Console.WriteLine(message);  
  60.     
  61.           return true;  
  62.       }  
  63.     
  64.       public static void Main()  
  65.       {  
  66.     
  67.           // Use interop to set a console control handler.  
  68.           MyWin32.HandlerRoutine hr = new MyWin32.HandlerRoutine(Handler);  
  69.           MyWin32.SetConsoleCtrlHandler(hr, true);  
  70.     
  71.           // Give the user some time to raise a few events.  
  72.           Console.WriteLine("Waiting 30 seconds for console ctrl events");  
  73.     
  74.           // The object hr is not referred to again.  
  75.           // The garbage collector can detect that the object has no  
  76.           // more managed references and might clean it up here while  
  77.           // the unmanaged SetConsoleCtrlHandler method is still using it.        
  78.     
  79.           // Force a garbage collection to demonstrate how the hr  
  80.           // object will be handled.  
  81.           GC.Collect();  
  82.           GC.WaitForPendingFinalizers();  
  83.           GC.Collect();  
  84.     
  85.           Thread.Sleep(10000);  
  86.     
  87.           // Display a message to the console when the unmanaged method  
  88.           // has finished its work.  
  89.           Console.WriteLine("Finished!");  
  90.     
  91.           // Call GC.KeepAlive(hr) at this point to maintain a reference to hr.   
  92.           // This will prevent the garbage collector from collecting the   
  93.           // object during the execution of the SetConsoleCtrlHandler method.  
  94.           GC.KeepAlive(hr);  
  95.           Console.Read();  
  96.       }  
  97.   }  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值