Proper use of C # destructor

So, I was looking for an implementation of the destructor for the class that I wrote, and I'm not sure how to really free the memory or if it will be handled by garbage collection.

class AutomatedTest
{
   public bool testComplete = false;
   public bool testStopRequest = false;

   public List<Command> commandList = new List<Command>();

   private bool loggingEnabled = false;
   ...


   public AutomatedTest(TestList testToCreate)
   {
       // Create a list of Command objects and add them to the list
   }
}  

How the class is used:

for(int numTests = 0; numTests < 20; numTests++)
{
    AutomatedTest test1 = new AutomatedTest(TestList._1DayTest);
    RunAutoTest(test1);

    AutomatedTest test2 = new AutomatedTest(TestList._2DayTest);
    RunAutoTest(test2);

    AutomatedTest test3 = new AutomatedTest(TestList._3DayTest);
    RunAutoTest(test3);

    AutomatedTest test4 = new AutomatedTest(TestList._4DayTest);
    RunAutoTest(test4);
}  

So, 4 objects are created and launched, and this is done 20 times.
My question is: how should I properly dispose / destroy these objects? I do not want to assume that this is garbage collection, but I am new to implementing descriptors.

+3
source share
7 answers

Until you use objects that implement IDisposable, you do not need to manually delete or destroy it.

+1
source

, . Henk Holterman, , , IDisposable IDisposable. , , .Dispose() , ~AutomatedTest()

, , test1 = null; , , .NET , , , , GC .

+1

IDisposable . , , , - , , , .. GC. .

0

, : " - IDisposable, ". , , , , . , , , .

MSDN .

0

"" Finalizer, , , .

, , , IDisposable.

0

IDisposable Dispose Finalize. , .

0

, . , #, . CLR ( ), , . ,

AutomatedTest test1 = new AutomatedTest(TestList._1DayTest);
RunAutoTest(test1);

RunAutoTest (test1) 'test1' . , , , . AutomatedTest , FileStream .., , , . , IDisposable .

class AutomatedTest:IDisposable
    {
        public void Dispose()
        {
            //free up any resources
        }
    }

IDisposable, , "using"

 for (int numTests = 0; numTests < 20; numTests++)
        {
            using (AutomatedTest test1 = new AutomatedTest(TestList._1DayTest))
            {
                RunAutoTest(test1);
            }
            //as soon as code exits the 'using' block the dispose method on test1 would be called
            //this is something you cannot guarantee when implementing a destructor

            using (AutomatedTest test2 = new AutomatedTest(TestList._2DayTest))
            {
                RunAutoTest(test2);
            }
            //dispose on test2 will be called here

            ///rest of code
        }  

FYI # ~. IDisposable

  class AutomatedTest
    {

        ~AutomatedTest()
        {
            //code will run only on garbage collection
        }
    }
0

All Articles