Home > Enterprise >  Do .NET finalizers have a timeout?
Do .NET finalizers have a timeout?

Time:03-24

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?

~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?

CodePudding user response:

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.

  • Related