【问题标题】:What is the notion behind 'Pinned GC handle'?“固定 GC 句柄”背后的概念是什么?
【发布时间】:2011-01-18 10:31:20
【问题描述】:

当我们分析内存堆时,我们一般会遇到以下 4 种类型的 GC 句柄:

  1. 弱:- 弱 GC 句柄不会阻止它对应的实例被垃圾回收。 Example, used by the System.WeakReference class instances.

  2. 正常:- 正常的 GC 句柄可防止相应的实例被垃圾回收。Example, used by the instances of strong references

  3. RefCounted:- 引用计数的 GC 句柄在运行时内部使用,example, when dealing with COM interfaces.

  4. Pinned:- 为什么我们需要这种 GC 句柄?只是为了避免该实例在内存中的移动还是is there any other notion behind this? I want to know the notion behind Pinned GC handle(with an example).

为 Itay 的答案编辑:- 我有一个非空数组-DiffCell[][] 绑定到数据网格WPF。当我关闭存在此数据网格的窗口时,在堆上我看到 Pinned GC 句柄 通过 DiffCell 指向这个空数组>object[](见快照)。 I am not using any unsafe code. I am just setting ItemsSource of data grid to null before closing that window. So my question is who does pin this array on heap and why?

【问题讨论】:

    标签: .net wpf garbage-collection


    【解决方案1】:

    我们需要这个以防我们使用指针。
    想象一下,您声明了一个指向内存位置的指针,但您没有固定。
    GC 有时会将内存块移动到其他位置,因此您的指针将变得无效。

    例如:

    public unsafe void DoSomething(byte b)
    {
       byte * bp = &b;
    }
    

    这将无法编译,因为您没有修复保存该字节的内存位置。
    为了固定它,您可以使用:

    public unsafe void DoSomething(byte b)
    {
       fixed(byte * bp = &b)
       {
            //do something
       }
    }
    

    【讨论】:

    • 谢谢伊泰!请查看已编辑的问题,并让我知道您的 cmets。
    • 我真的不知道 WPF 和绑定是如何工作的,所以在这里我恐怕无法为您提供帮助。
    【解决方案2】:

    不要忘记GCHandle,它支持固定对象(并将地址检索为IntPtr)。固定对象并不是不安全代码所独有的(固定语句)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 2011-01-15
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多