Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do .NET finalizers have a timeout?

Edits – Renamed to finalizer per answer

I am trying to do a few things in a finalizer, and the program terminates before I’m done. To simulate, I made the following test, which prints up to 20

Does this mean .NET finalizer "timeout" after 2 seconds?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

~MyClass()
{
    // do some cleaup
    int i = 0;
    while (true)
    {
        Console.WriteLine(i++);
        Thread.Sleep(100);
    }
}

For context, I have some background threads (Task objects) that’s I’d like to terminate gracefully. I’m just testing to see how long it takes to do it from the finalizer.

What’s a better design pattern for doing this? Perhaps have a "Shutdown" method that I have to make sure is called when closing a form? I know finalizers are meant for cleanup of unmanaged memory, but it seems nice to stop all my threads since I know it will be called.

Maybe I just let the threads terminate abruptly and not worry about it?

>Solution :

First, I should note that "destructors" are now more commonly referred to as "finalizers", as the former term implies these special methods work like destructors in C++, but they really don’t. So you might have better luck searching if you use the newer term.

To your question, yes, there is evidence that .NET has a time limit on finalizers during shutdown – common quotes say one finalizer taking more than 2 seconds, or all finalizers taking 40 seconds – will cause the runtime to give up and just shutdown without continuing to let finalizers run.

I would recommend looking into implementing IDisposable to handle cleanup deterministically. C# has syntax sugar – the using statement – to help make this easier on the consumer’s side.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading