When is it acceptable to call GC.Collect?

前端 未结 24 2460
挽巷
挽巷 2020-11-22 08:54

The general advise is that you should not call GC.Collect from your code, but what are the exceptions to this rule?

I can only think of a few very speci

24条回答
  •  天涯浪人
    2020-11-22 09:29

    In large 24/7 or 24/6 systems -- systems that react to messages, RPC requests or that poll a database or process continuously -- it is useful to have a way to identify memory leaks. For this, I tend to add a mechanism to the application to temporarily suspend any processing and then perform full garbage collection. This puts the system into a quiescent state where the memory remaining is either legitimately long lived memory (caches, configuration, &c.) or else is 'leaked' (objects that are not expected or desired to be rooted but actually are).

    Having this mechanism makes it a lot easier to profile memory usage as the reports will not be clouded with noise from active processing.

    To be sure you get all of the garbage, you need to perform two collections:

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

    As the first collection will cause any objects with finalizers to be finalized (but not actually garbage collect these objects). The second GC will garbage collect these finalized objects.

提交回复
热议问题