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