When is it acceptable to call GC.Collect?

前端 未结 24 2174
挽巷
挽巷 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:15

    One useful place to call GC.Collect() is in a unit test when you want to verify that you are not creating a memory leak (e. g. if you are doing something with WeakReferences or ConditionalWeakTable, dynamically generated code, etc).

    For example, I have a few tests like:

    WeakReference w = CodeThatShouldNotMemoryLeak();
    Assert.IsTrue(w.IsAlive);
    GC.Collect();
    GC.WaitForPendingFinalizers();
    Assert.IsFalse(w.IsAlive);
    

    It could be argued that using WeakReferences is a problem in and of itself, but it seems that if you are creating a system that relies on such behavior then calling GC.Collect() is a good way to verify such code.

提交回复
热议问题