Sebastian Krysmanski
Sebastian Krysmanski

Reputation: 8404

Under which circumstances does GC.WaitForPendingFinalizers() block in .NET?

Quoting from the MSDN documentation for GC.WaitForPendingFinalizers():

The thread on which finalizers are run is unspecified, so there is no guarantee that this method will terminate.

I don't really understand this sentence. Under which circumstances does this method not terminate? And what does this have to do with the thread the finalizer runs on? Why do they state that the thread is "unspecified"?

Regarding the finalizer thread, I assume the following is correct(?):

Note: I can imagine this method will block when one of the finalizers blocks, but this problem exist no matter what thread is being used for the finalizers.

Upvotes: 2

Views: 1193

Answers (2)

Richard Morgan
Richard Morgan

Reputation: 7691

From another article on MSDN:

The Finalize method might not run to completion or might not run at all in the following exceptional circumstances:

  • Another finalizer blocks indefinitely (goes into an infinite loop, tries to obtain a lock it can never obtain and so on). Because the runtime attempts to run finalizers to completion, other finalizers might not be called if a finalizer blocks indefinitely.

  • The process terminates without giving the runtime a chance to clean up. In this case, the runtime's first notification of process termination is a DLL_PROCESS_DETACH notification.

Upvotes: 2

Shahar Gvirtz
Shahar Gvirtz

Reputation: 2438

First, you usually don't need to use methods in GC class, except probably for SuppressFinalize. Most of the other methods will usually makes you application performs worst, not better.

But, to answer your questions, as far as i know when collection performed there is internal list held by the garbage collector of finalizers to run, and they all run sequencally on the same thread. Which means, that if one finalizer block then i guess this method will block too.

When app domain shuts down, there is a time limit for all finalizers to finish, and in that case i guess it doesn't really matter.

Upvotes: 1

Related Questions