Why GC.Collect() call twice required when use GC.WaitForPendingFinalizers();

T.Zacks 3,996 Reputation points
2021-04-09T08:55:57.223+00:00

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

1) What WaitForPendingFinalizers does ?
it suspend the current thread and clear the memory?

2) Why GC.Collect(); called twice when we use GC.WaitForPendingFinalizers(); ?

3) GC.WaitForPendingFinalizers(); slow down the performance of the application....why ?

Thanks

Developer technologies C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,651 Reputation points
    2021-04-12T07:10:48.937+00:00

    Hi TZacks-2728,

    1. As you said, GC.WaitForPendingFinalizers method is used to suspend the current thread until the thread that is processing the queue of finalizers has emptied that queue.
    2. If you have code in your finalizers, it's possible that you will need to call GC.Collect() twice, as the first time will cause the finalizers to execute, but the actual memory cannot be cleaned until after the finalizer has completed, which means the subsequent call will catch the object.
      Here are some related threads you can refer to.
      Will GC.Collect() + GC.WaitForPendingFinalizers() ever NOT reclaim all reclaimable memory?
      Is correct to use GC.Collect(); GC.WaitForPendingFinalizers();?
    3. From offical document said, it's possible to force garbage collection by calling Collect. But most of the time, this call should be avoided because it may create performance issues.
      Best Regards,
      Daniel Zhang

    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.