Naveen Kumar V
Naveen Kumar V

Reputation: 2809

Destructor ends before completing its task in C#?

The following destructor code in desctructorCheck class closes the console, after almost 2 seconds, before getting any input from user.

~destructorCheck() {
   Console.WriteLine("Destructor");
   Console.ReadLine( );
}

Why it is closing? Do destructor have any timer to finish its cleanup process?

Upvotes: 0

Views: 134

Answers (2)

Michael Edenfield
Michael Edenfield

Reputation: 28338

Yes. Finalizers have a limited amount of time to run before they will be terminated.

This is one of the many reasons that finalizers are a tool of last resort. They aren't guaranteed to run in the first place, and not guaranteed to finish. They are only running because the Framework really needs that object to go away now -- it's either GC'ing it because it needs memory, or your application is shutting down.

I'm pretty sure the time limit is ~2 seconds, and I don't know of any way to change it.

Upvotes: 2

Russ Clarke
Russ Clarke

Reputation: 17909

The reason is, because of how Destructors are called:

To quote MSDN:

'The programmer has no control over when the destructor is called because this is determined by the garbage collector. The garbage collector checks for objects that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor (if any) and reclaims the memory used to store the object. Destructors are also called when the program exits.'

I agree that reading Eric Lippert's blog is a good thing!

If you need to ensure something happens when your C# object is being destroyed, you should probably implement IDisposable and put your closure logic into the Dispose method.

Upvotes: 2

Related Questions