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 = ,
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的使用的更多相关文章
随机推荐
- SQL Server Replication issues-the row was not found at the subscriber end
Issue type: 1.find out the number 0x0006F18F00006082002300000000 from publication end. 2.use below s ...
- Sql Server中实现Mysql中的group_concat函数效果
), GuestName) , , '') as CustomerName FROM orderitem oi 以上涉及的两个表是OrderItem和Guest,以属性OrderSN和ItemId连接 ...
- svn-多个项目版本库和自动同步更新post-commit
由于项目测试需求,需要远程服务器上使用svn做版本控制. 需求: 1,项目test1,项目test2,各自独立版本库,各自独立用户权限,便于项目管理 2,同步提交,本地svn提交至版本库后,服务器上的 ...
- java_ee_sdk-7u2的安装与 启动
1.在oracle官方网站上下载JAVA EE SDK,现在最新的版本是java_ee_sdk-7u2 2.最新的版本是免安装模式,所以比较方便.但是通常免安装模式没有快捷方式,不知道怎么启动.怎么使 ...
- 反斜杠在JSP中的两种不同的含义
/ 在不同条件下的不同含义 / 代表WEB应用的根路径的情况:/ 交给 Servlet容器来处理 请求转发时: request.getRequestDispatcher("/xxxx&quo ...
- mybatis输出SQL
1.导包 下载一个log4j-1.2.17.jar,放到WEB-INF的lib下,并加入build path 2.创建配置文件 在src下创建log4j.properties,填入以下内容: log4 ...
- WinDbg 蓝屏dump分析教程
一.WinDbg是什么?它能做什么? WinDbg是在windows平台下,强大的用户态和内核态调试工具.它能够通过dmp文件轻松的定位到问题根源,可用于分析蓝屏.程序崩溃(IE崩溃)原因,是我们日常 ...
- Redis一个异常的解决办法,异常描述:Could not get a resource from the pool
异常描述: redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the poo ...
- 安装LoadRunner提示缺少vc2005_sp1_with_atl..
装自动化负载测试工具LoadRunner前,需要预先安装其运行的基础环境.如:安装LoadRunner 11时就需要先安装Micrsoft Visual C++ 2005 SP1.C++ 2008运行 ...
- C#获取并写入ORACLE数据库中中英文字符集问题
背景: 开发语言:C# 开发工具:VS2010 A方ORACLE数据库:中文字符集 B方ORACLE数据库:英文字符集 传递方式:webservice方式(取数据,并把取出的数据放到DataTable ...