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

I was wondering when, in these circumstances, the destructor is called, and if it is called in the main UI thread?

Let's say I have the following code when the destructor is called, and will it wait until I finish 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? 

This is what interests me if the thread breaks in myObj = new MyObject (), or if the call to Destructor waits until Thread is free.

Thanks for the info.

+6
c # destructor
source share
5 answers

Destructor is called when the garbage collector decides that it should clear some old objects. You cannot rely on runtime destructors in .NET

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

See Deployment Method Implementation

+17
source share

If it is important to manage the lifetime of your objects, inherit from IDisposible, and you can use using the keyword .

+3
source share

Destructors or finalizers, as they are also called, are called at some point in time after your instance is available for garbage collection. This does not happen at a determinate point in time, as in C ++.

+2
source share

Destructors (or finalizers, some prefer to call them) are executed in a separate chain. They start at a specific time. They are not guaranteed to run until the end of the life of the applications, and even then, perhaps they will not be called.

+2
source share

The destructor (finalizer) is called as soon as the garbage collector can determine that your object is no longer in use. Finalizers run the finalizer stream, simultaneously into your main program!

With proper optimization (the JIT compiler can easily remove the local variable), it can already be inside the first DoSomeFunThingsWithMyObject call (as soon as this method doesn’t need its parameter anymore), or at any other time. Maybe it’s not even called until your program is closed (and in rare cases, the finalizer is never called).

+1
source share

All Articles