Is correct to use GC.Collect(); GC.WaitForPendingFinalizers();?

前端 未结 6 1957
南笙
南笙 2020-12-02 17:03

I\'ve started to review some code in a project and found something like this:

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

Those lines usua

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 17:52

    See my other answer here:

    To GC.Collect or not?

    two things can happen when you call GC.Collect() yourself: you end up spending more time doing collections (because the normal background collections will still happen in addition to your manual GC.Collect()) and you'll hang on to the memory longer (because you forced some things into a higher order generation that didn't need to go there). In other words, using GC.Collect() yourself is almost always a bad idea.

    About the only time you ever want to call GC.Collect() yourself is when you have specific information about your program that is hard for the Garbage Collector to know. The canonical example is a long-running program with distinct busy and light load cycles. You may want to force a collection near the end of a period of light load, ahead of a busy cycle, to make sure resources are as free as possible for the busy cycle. But even here, you might find you do better by re-thinking how your app is built (ie, would a scheduled task work better?).

提交回复
热议问题