2

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?

stevep
  • 167
  • 1
  • 7

1 Answers1

6

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.

Joe Sewell
  • 6,067
  • 1
  • 21
  • 34
  • OK, thank you. I'll check into the IDisposable implementation – stevep Mar 23 '22 at 20:39
  • 1
    Note that for .NET Core these limits, it seems, are not [applicable](https://github.com/dotnet/docs/issues/17463#issuecomment-600327712) – Guru Stron Mar 23 '22 at 20:50