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.
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
If it is crucial that the lifetime of your objects is managed, inherit from IDisposible and you can use the using keyword.
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++.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With