![](/img/trans.png)
[英]Does a reference to a delegate constitute a reference to an object (to prevent garbage collection)?
[英]Does keeping a reference to an object as a member prevent collection?
考慮以下代碼,其中類A負責管理本機數據。 指向該數據的指針傳遞給B類,因此我需要在使用B時不收集A:
class A
{
public A(string n)
{
_n = n;
_p = IntPtr.Zero; //acquire native resource
}
public IntPtr GetP()
{
return _p;
}
~A()
{
Console.WriteLine("Free native resource {0}", _n);
}
string _n;
IntPtr _p;
};
class B
{
public B(IntPtr p)
{
_p = p;
}
public B(IntPtr p, Object o)
{
_p = p;
_o = o;
}
public IntPtr GetP()
{
return _p;
}
IntPtr _p;
Object _o;
};
如果我沒有從“ b”中引用“ a”,那么“ a”會按預期立即收集,這使我有了指向無效數據的指針(至少在Visual Studio中,mono中的gc並不那么急切):
static void Main(string[] args)
{
var a = new A("a");
var b = new B(a.GetP());
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("b._p: {0}", b.GetP());
}
Output:
Free native resource a
b._p: 0
但是,如果我持有從“ b”到“ a”的引用,則即使以后不再使用“ a”,也不會釋放“ a”直到退出:
static void Main(string[] args)
{
var a = new A("a");
var b = new B(a.GetP(), a);
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("b._p: {0}", b.GetP());
}
Output:
b._p: 0
Free native resource a
所以我的問題是:在第二種情況下,規范a保證'a'處於活動狀態,而'b'未被收集,還是此行為實現依賴? 如果是后者,我將如何繼續保持下去? 我已經看到了幾個類似的問題,但沒有找到確切的答案。
所以我的問題是:在第二種情況下,規范中保證“ a”有效,而未收集“ b”時,
是。 如果b
引用了a
並且未收集,則a
也將不會收集。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.