I've heard several people asking why GCHandle doesn't implement IDisposable, considering it wraps an unmanaged resource (a handle) and needs to be explicitly freed (using GCHandle.Free()). Before I explain the reason, I want to give a little background on GCHandles and their dangers.

What's a GCHandle?

A GCHandle is a struct that contains a handle to an object. It's mainly used for holding onto a managed object that gets passed to the unmanaged world to prevent the GC from collecting the object. You can also create a Pinned GCHandle to a managed object and retrieve the object's address in memory.

How are GCHandles dangerous?

When you create a new GCHandle, a new entry in the AppDomain's handle table is created. This entry is kept until the handle is freed (via GCHandle.Free()) or the AppDomain is unloaded.

Things get tricky if you were to make a copy of a GCHandle:

Object obj = new Object();
GCHandle gch = GCHandle.Alloc(obj, GCHandleType.Normal);
GCHandle gch2 = gch;

Since
GCHandle is value type, gch2 has its own copy of the handle. You now
have two handles that point to the same entry in the handle table.
Unfortunately, since gch2 is a copy of –not a reference to– gch,
anything that happens to gch doesn't happen to gch2. For example,
calling gch.Free() will delete the entry from the handle table, but not
update gch2, so gch2.IsAllocated will return true, but gch2.Target will
be null. The same problem arises with casting to and from IntPtrs, and
when GCHandles get boxed. Unlike double-freeing a single GCHandle,
freeing the copy will NOT throw an InvalidOperationException. You have
to be very careful not to double-Free your handles since this can
corrupt the handle table.

Why don't GCHandles implement IDisposable?

One
of the main purposes of IDisposable to avoid the use of finalizers.
This is because finalizers are not run deterministically, and result in
promoting a finalizable object a generation, effectively keeping in
memory longer. Since GCHandle is a value type, it has no finalizer, and
is not collected by the GC, so these problems are eliminated. Another
other main use of IDisposable is to clean up unmanaged resources as soon
as you are done with them. With a GCHandle, the resource is the handle
which is cleaned up by calling GCHandle.Free(). If Free isn't called,
the handle gets cleaned up when the appdomain is unloaded.

One
of the side effects of having a struct implement IDisposable, is that
users may be tempted to cast their GCHandles as IDisposable, which boxes
the GCHandle into an IDisposable object on the heap, and the two
GCHandles get out-of-sync. The same problem arises with the putting a
disposable struct into a using block:

struct Test : IDisposable
{
    public bool disposed; // initialized to false
    public void Dispose()
    {
        disposed = true;
    }
}

public void Foo()
{
    Test t = new Test();
    using (t)
    {
        // do stuff
    }

if (!t.disposed)
    {
        t.Dispose();
    }
}

t.disposed
will return false, since it was a copy of t whose Dispose method was
called. If t were a GCHandle, then the handle would be removed from the
appdomain's handle table, and calling Free after the using would result
in a double Free, even though IsAllocated would return true!

Remember,
GCHandles are advanced structures, and one should be very careful to
ensure they are cleaned up properly. Unfortunately, IDisposable makes it
easy to get this wrong, so the BCL designers erred on the side of
caution, and gave GCHandle a Free() method to use.

The Truth About GCHandles的更多相关文章

  1. hdu3729 I'm Telling the Truth (二分图的最大匹配)

    http://acm.hdu.edu.cn/showproblem.php?pid=3729 I'm Telling the Truth Time Limit: 2000/1000 MS (Java/ ...

  2. windbg 命令 gchandles

    使用windbg导出dump文件 .dump /ma D:\testdump.dmp gchandles命令列出句柄,同时列出句柄引用的对象,演示代码如下: using System; using S ...

  3. I'm Telling the Truth(二分图)

    .I'm Telling the Truth Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Othe ...

  4. 论文笔记之:Playing for Data: Ground Truth from Computer Games

    Playing for Data: Ground Truth from Computer Games ECCV 2016 Project Page:http://download.visinf.tu- ...

  5. codeforces Gym 100187L L. Ministry of Truth 水题

    L. Ministry of Truth Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/gym/100187/p ...

  6. Codeforces Gym 100610 Problem H. Horrible Truth 瞎搞

    Problem H. Horrible Truth Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/gym/1006 ...

  7. 关于warning: suggest parentheses around assignment used as truth value [-Wparentheses]|的解决方法

    今天,在调试的时候一直出现warning: suggest parentheses around assignment used as truth value 代码如下: if(startTime== ...

  8. Pretty Smart? Why We Equate Beauty With Truth

    Pretty Smart? Why We Equate Beauty With Truth With some regularity we hear about the latest beauty-p ...

  9. [usaco]2013-jan Liars and Truth Tellers 真假奶牛

    Description 约翰有N头奶牛,有一部分奶牛是真话奶牛,它们只说真话,而剩下的是假话奶牛,只说假话.有一天,约翰从奶牛的闲谈中陆续得到了M句话,第i句话出自第Xi头奶牛,它会告诉约翰第Yi头是 ...

随机推荐

  1. Linq的优缺点

    优点: 1.Linq提供了不同数据源的抽象层,所以可以使用相同的语法访问不同的数据源(只要该数据源有提供程序即可) 2.Linq为底层的数据存储提供了一个强类型化的界面,可以把底层的数据作为对象来访问 ...

  2. cmake policy

    1 cmake policy是什么? cmake policy可以理解为cmake的语法标准,也就是说,它规定了cmake在解析CMakeLists.txt文件时的行为. 2 cmake policy ...

  3. mysql系列之4.mysql字符集

    针对mysql语句的临时办法: 先查看下mysql的各种编码设置情况, 如果结果显示有几项的编码不一致, 请先调整linux的系统编码 mysql> show variables like 'c ...

  4. Grunt学习笔记【6】---- grunt-contrib-requirejs插件详解

    本文主要讲如何使用Grunt实现RequireJS文件压缩. 一 说明 ES6出来前,RequireJS是JavaScript模块化最常用的方式之一.对于使用RequireJS构建的项目,要实现打包压 ...

  5. centos 7 PostgreSQL一些简单问题以及解决办法

    问题:org.postgresql.util.PSQLException: Connection refused. Check that the hostname and port are corre ...

  6. SpringBoot学习笔记(12):计划任务

    SpringBoot学习笔记(12):计划任务 计划任务 在企业的实践生产中,可能需要使用一些定时任务,如月末.季末和年末需要统计各种各样的报表,每周自动备份数据等. 在Spring中使用定时任务 1 ...

  7. uboot 2013.01 代码简析(2)第一阶段初始化

    uboot执行"make smdk2410_config"之后就可以进行编译了,可以执行make命令进行编译, 因为整个输出太长,我仅仅列出部分最关键的输出(部分我不关心的内容直接 ...

  8. 【博弈论】hihocoder

    #1163 : 博弈游戏·Nim游戏 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 今天我们要认识一对新朋友,Alice与Bob. Alice与Bob总是在进行各种各样 ...

  9. 51Nod 1158 全是1的最大子矩阵 —— 预处理 + 暴力枚举 or 单调栈

    题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1158 1158 全是1的最大子矩阵  基准时间限制:1 秒 空 ...

  10. 1.1 BASIC PROGRAMMING MODEL(算法 Algorithms 第4版)

    1.1.1 private static void exercise111() { StdOut.println("1.1.1:"); StdOut.println((0+15)/ ...