Best Practice for Forcing Garbage Collection in C#

前端 未结 15 1988
天命终不由人
天命终不由人 2020-11-22 12:28

In my experience it seems that most people will tell you that it is unwise to force a garbage collection but in some cases where you are working with large objects that don\

15条回答
  •  庸人自扰
    2020-11-22 12:31

    The best practise is to not force a garbage collection in most cases. (Every system I have worked on that had forced garbage collections, had underlining problems that if solved would have removed the need to forced the garbage collection, and sped the system up greatly.)

    There are a few cases when you know more about memory usage then the garbage collector does. This is unlikely to be true in a multi user application, or a service that is responding to more then one request at a time.

    However in some batch type processing you do know more then the GC. E.g. consider an application that.

    • Is given a list of file names on the command line
    • Processes a single file then write the result out to a results file.
    • While processing the file, creates a lot of interlinked objects that can not be collected until the processing of the file have complete (e.g. a parse tree)
    • Does not keep much state between the files it has processed.

    You may be able to make a case (after careful) testing that you should force a full garbage collection after you have process each file.

    Another cases is a service that wakes up every few minutes to process some items, and does not keep any state while it’s asleep. Then forcing a full collection just before going to sleep may be worthwhile.

    The only time I would consider forcing a collection is when I know that a lot of object had been created recently and very few objects are currently referenced.

    I would rather have a garbage collection API when I could give it hints about this type of thing without having to force a GC my self.

    See also "Rico Mariani's Performance Tidbits"

提交回复
热议问题