I'm trying to understand how the GC acts when an object is not being used anymore, my test is to do nothing with the object (after used) but it didn't work, the object's destructor was never called.
I've created an example program trying to wait until the object is destroyed, but after 4 hours running nothing happens.
Note: I know if I set the object to null the GC will collect it, but I just want to see the "normal" way the GC itself collects the object.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
internal class Program
{
private const string FilePath = @"C:\objLifeCycle.txt";
private static void Main(string[] args)
{
var result = GetList();
Console.WriteLine("Results received! Object Id: [{0}] time: [{1}]", result.ObjId, DateTime.Now);
//result = null;
Task.Factory.StartNew(() =>
{
while (true)
{
Thread.Sleep(2000);
Console.WriteLine("...");
GC.Collect();
}
});
Console.ReadKey();
}
private static LinkList GetList()
{
return new LinkList(FilePath) { "link1", "link2", "link3" };
}
}
}
internal class LinkList : List<string>
{
internal string ObjId { get; set; }
internal string FilePath { get; set; }
internal LinkList(string filePath)
{
ObjId = Guid.NewGuid().ToString();
FilePath = filePath;
WriteFile($"Object LinkList with Id [{ObjId}] has been created at [{DateTime.Now}]");
}
~LinkList()
{
WriteFile($"Object LinkList with Id [{ObjId}] has been destroyed at [{DateTime.Now}]");
Environment.Exit(0);
}
private void WriteFile(string line)
{
var sw = new StreamWriter(FilePath, true);
sw.WriteLine(line);
sw.Close();
}
}