C
C#2y ago
anita

✅ I don't understand GC

The output of this code is True, False. Why? Both instances of Class1 don't have any reference pointing to them. But only one of them is garbage collected. What am I missing?
var we = Method1();
Console.WriteLine(IsGcCollected(we));

Method2();

[MethodImpl(MethodImplOptions.NoInlining)]
WeakReference Method1()
{
var c = new Class1(1);
return new WeakReference(c);
}

[MethodImpl(MethodImplOptions.NoInlining)]
void Method2()
{
var c = new Class1(1);
var w = new WeakReference(c);
c = null;
Console.Write(IsGcCollected(w));
}

bool IsGcCollected(WeakReference w)
{
for (var i = 0; w.IsAlive && i < 10; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}

return !w.IsAlive;
}

class Class1{
public Class1(int propterty1)
{
Propterty1 = propterty1;
}

public int Propterty1 { get; set; }
}

var we = Method1();
Console.WriteLine(IsGcCollected(we));

Method2();

[MethodImpl(MethodImplOptions.NoInlining)]
WeakReference Method1()
{
var c = new Class1(1);
return new WeakReference(c);
}

[MethodImpl(MethodImplOptions.NoInlining)]
void Method2()
{
var c = new Class1(1);
var w = new WeakReference(c);
c = null;
Console.Write(IsGcCollected(w));
}

bool IsGcCollected(WeakReference w)
{
for (var i = 0; w.IsAlive && i < 10; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}

return !w.IsAlive;
}

class Class1{
public Class1(int propterty1)
{
Propterty1 = propterty1;
}

public int Propterty1 { get; set; }
}

2 Replies
WhiteBlackGoose
thinkinggura no idea, try #advanced or #allow-unsafe-blocks
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity. Closed!
Want results from more Discord servers?
Add your server