question

TZacks-2728 avatar image
0 Votes"
TZacks-2728 asked DanielZhang-MSFT edited

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

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

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

DanielZhang-MSFT avatar image
0 Votes"
DanielZhang-MSFT answered DanielZhang-MSFT edited

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.



5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.