If there is an object with infinite loop, will it ever be garbage collected (while thread is running)?
I made a program to test this and it seems it will never be garbage collected, but I'd like someone with more experience to confirm this.
EDIT: I forgot to add example. Here is example which I have used.
class Program
{
static void Main(string[] args)
{
WeakReference wr1 = InitializeClassWithLoop();
WeakReference wr2 = InitializeClassWithoutLoop();
GC.Collect(2);
GC.Collect(2);
GC.Collect(2);
GC.WaitForPendingFinalizers();
Thread.Sleep(30000);
Console.WriteLine($"ClassWithLoop.IsAlive = {wr1.IsAlive}\nClassWithoutLoop.IsAlive = {wr2.IsAlive}\n");
Console.ReadLine();
}
static WeakReference InitializeClassWithLoop()
{
var cs = new ClassWithLoop();
return new WeakReference(cs);
}
static WeakReference InitializeClassWithoutLoop()
{
var cs = new ClassWithoutLoop();
return new WeakReference(cs);
}
}
public class ClassWithLoop
{
public ClassWithLoop()
{
Thread thread = new Thread(Loop);
thread.Start();
}
private void Loop()
{
int counter = 0;
while (true)
{
counter++;
Thread.Sleep(1000);
}
}
}
public class ClassWithoutLoop
{
int counter;
public ClassWithoutLoop()
{
counter = 5;
}
}
Result is:
ClassWithLoop.IsAlive = True
ClassWithoutLoop.IsAlive = False