Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is my destructor called in this circumstance? (C#)

I was wondering when the destructor is called under these circumstances, and if it is will it be called on the main UI thread?

Let's say I have the following code, when would the destructor be called, and would it wait until I have finished all my function calls?

private void Foo()
  {
  MyObject myObj = new MyObject();
  DoSomeFunThingsWithMyObject(myObj);

  myObj = new MyObject(); //is the destructor for the first instance called now?
  DoLongOminousFunctionality(myObj);  
  }
  //Or will it be called after the DoLongOminousFunctionality?

It's just something that interests me, if the thread is interrupted at myObj = new MyObject(), or if the Destructor call waits until the Thread is free.

Thanks for the information.

like image 224
Lloyd Powell Avatar asked Aug 11 '09 10:08

Lloyd Powell


4 Answers

Destructor will be called when Garbage collector decides that it have to clean up some old objects. You cannot rely on destructors execution time in .NET

Instead of that you should use Dispose() if you want to clean up some resources when they are not needed (especially when you have any unmanaged resources such as TCP connections, SQL connections etc.)

See Implementing a Dispose Method

like image 169
Bogdan_Ch Avatar answered Oct 25 '22 10:10

Bogdan_Ch


If it is crucial that the lifetime of your objects is managed, inherit from IDisposible and you can use the using keyword.

like image 22
DanDan Avatar answered Oct 25 '22 11:10

DanDan


Destructors or finalizers as they are also named are called at some point in time after your instance is available for garbage collection. It doesn't happen at a deterministic point in time as in C++.

like image 2
Brian Rasmussen Avatar answered Oct 25 '22 12:10

Brian Rasmussen


Destructors (or finalizers are some people prefer to call them) are run on a seperate thread altogether. They are run at no particular time. They aren't guaranteed to run at all till the end of your applications life, and even then it's possible they won't get called.

like image 2
Matthew Scharley Avatar answered Oct 25 '22 12:10

Matthew Scharley