Igor datsko
Igor datsko

Reputation: 1

System dectruct of objects

Please, tell me why ~Destruct() waits to delete objects in my code until the end? I thought that destruct must create an object and immediately delete it. But my code creates 10000 objects, and only when that is done does it then delete the 10000. Why?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace project6
{
    class Destruct
    {
        public int x;
        public Destruct(int i)
        {
            x = i;
        }
        ~Destruct()
        {
            Console.WriteLine("\n"+ x +" - Обьект разрушен");
        }
        public void generator(int i)
        {
            Destruct obj = new Destruct(i);
        }
    }


    class Program
    {
        static void Main()
        {
            Destruct o = new Destruct(0);
            for(int a=0;a<10000;a++)
            {
                o.generator(a);    
            }
            Console.WriteLine("Готово");
            }
    }
}

Upvotes: 0

Views: 32

Answers (2)

Gary Kaizer
Gary Kaizer

Reputation: 284

The reason that the ~Destruct is called AFTER you loop is that the ~Destruct() function will be called only when the garbage collector runs. If you force the garbage collector to run they your objects will be immediately destroyed upon going out of scope.

        for(int a=0;a<10000;a++)
        {
            o.generator(a); 

            //This will IMMEDIATLY destroy the object created by o.generator
            GC.Collect()   
        }

You probably never really want to do this in real code and let the GC (garbage collector) run whenever it needs to since it's going to be much smarter about when to clean up the memory.

Upvotes: 0

Steven Hansen
Steven Hansen

Reputation: 3239

C# uses garbage collection to delete objects. It doesn't necessarily run the moment every object goes out of scope - those objects are merely "queued" for deletion. That is why all your objects are created, and THEN all deleted.

Basically, you don't know exactly when the garbage collector is going to run.

Upvotes: 2

Related Questions