Dot-Net
“固定 GC 句柄”背後的概念是什麼?
當我們分析記憶體堆時,我們通常會遇到以下 4 種類型的 GC 句柄:
- 弱:- 弱 GC 句柄不會阻止它對應的實例被垃圾收集。
Example, used by the System.WeakReference class instances.- 正常:- 正常的 GC 句柄可防止相應的實例被垃圾收集。
Example, used by the instances of strong references.- RefCounted:- 引用計數的 GC 句柄在執行時內部使用,
example, when dealing with COM interfaces.- 固定:-為什麼我們需要這種 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數組**$$ $$***(見快照)。
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?
我們需要這個以防我們使用指針。
想像一下,您聲明了一個指向記憶體位置的指針並且您沒有固定
。GC 有時會將記憶體塊移動到其他位置,因此您的指針將變得無效。
例如:
public unsafe void DoSomething(byte b) { byte * bp = &b; }這不會編譯,因為您沒有修復保存字節的記憶體位置。
為了固定它,您可以使用:
public unsafe void DoSomething(byte b) { fixed(byte * bp = &b) { //do something } }
不要忘記支持固定對象的GCHandle(並將地址作為IntPtr檢索)。固定對象並不是不安全程式碼(固定語句)所獨有的。
