is it smart to use GC.Collect on application that

2019-05-03 08:16发布

问题:

We have application that runs 24h per day and 7 days per week. Sometimes CPU go to 100% and then go back to 80%. The same with RAM. Is it smart to manually call GC.Collect after few hours or betterto leave it automatically.

We are using C# 2010, SQL 2008 and Fluent Nhiberanet. This is desktop application.

回答1:

I wouldn't call it smart to call GC.Collect() "every few hours", or "when RAM usage goes to high", but I'd call it smart to call it whenever you are in a position of having more information than the GC, some exmaples

  • You know, this big chunk of RAM or these many small objects you just allocated, will not be used again and you are in a singlethreaded environment and (ofcourse) you have cleared all your references
  • You know, that a "GC break" will hurt less right now, than a bit later

The GC is a highly optimized peace of code and quite smart, but it can only work on information it has.



回答2:

Manually call the GC.Collect is never a good idea as you should investigate why your app is getting that much resources instead of clean them up every time you are about to reach 100%

Have a look at the below I think it really worth a read

Chapter 5 — Improving Managed Code Performance



回答3:

normally the framework itself will handle calling the GC when it's needed you could try to run it without calling it yourself for a day



回答4:

GC.Collect won't magically solve problems if you hold unnecessary references or forget to unsubscribe from delegates. The framework collects garbage by itself from time to time, so I don't believe calling GC.Collect every few hours can change anything.



回答5:

Short answer: no.

The garbage collector is not an area you want to be going into unless you have to. Normally the .net runtime does a pretty good job of calling it whenever it's needed. If you call it yourself it will just be additional overhead.



回答6:

I would refrain from calling GC.Collect - exceptional cases as described here and here aside.

IF you have any application running 24/7 then I would recommend the following:

  • check real hard for memory leaks and correct any such leak (using multiple memory profilers)
    IF you need any links please say so...

  • try your very best to reduce resource usage by optimizing/rewriting your code

  • configure the application to use GC in "server mode" as that is designed for 24/7 situations (for details see here)
    This is not a miracle solution but something you should try with your application and compare whether it gives you any benefits.