0

Possible Duplicate:
When is it acceptable to call GC.Collect?

Is Using of GC.Collect Method necessary and is it a good practice?
If yes, when should I use this method?
If No, Why?

Edit: Accourding to MSDN What is the meaning of: Use this method to try to reclaim all memory that is inaccessible.

Community
  • 1
  • 1
Navid Rahmani
  • 7,848
  • 9
  • 39
  • 57
  • 2
    Very similar question: http://stackoverflow.com/questions/478167/when-is-it-acceptable-to-call-gc-collect – Matt Jul 04 '11 at 14:42

4 Answers4

4

As a general rule... don't use it.

GC.Collect force a collection by the garbage collector, which, among other things, means pausing all the threads of the program so that the garbage collector can verify which objects are no longer referenced and claim the unused memory.

Usually the GC will automatically decide when he should collect memory, considering when your program is idle or if the allocated memory (virtual memory) is getting low so in order to allocate more it needs to free some. In my experience the .NET GC (as in Microsoft) is pretty intelligent and does what it does ratter well. Other GCs (as in mono) I don't have experience with them, but still probably will do a better job than the developer deciding when to perform a collection.

That, of course, has a good impact in performance and, as with many other situations, it knows better than you do the best time to perform a collection (in 99% of the cases that's true). So no, it's not a good practice and you should only do it when you have a really good reason to do it... a deep understanding of what it does and the possible consequences it may have.

ICR
  • 13,896
  • 4
  • 50
  • 78
Jorge Córdoba
  • 51,063
  • 11
  • 80
  • 130
2

Not generally recommended; not generally considered good practice.

In general the GC knows better than you what needs cleaning up, and when. Best practice is to leave the GC alone to do its business unhindered unless you have concrete proof that the GC's strategy is causing problems that can be solved by forcing it to behave differently.

LukeH
  • 263,068
  • 57
  • 365
  • 409
1

It is usually not necessary, and usually not a good idea to use it.

There are times when you need to use it but usually you are forcing a collect at a not optimal time, which have a performance hit.

There is good discussion on the matter here and here.

svick
  • 236,525
  • 50
  • 385
  • 514
Robert Anton Reese
  • 535
  • 1
  • 7
  • 18
-2

I have explained a few things relevant here:

WPF memory leak

Community
  • 1
  • 1
Aliostad
  • 80,612
  • 21
  • 160
  • 208
  • Why?!! That was **my** answer. Was it better to copy and paste from my own answer?? – Aliostad Jul 04 '11 at 15:03
  • 3
    It would be better (required) to at least give a summary. Otherwise a comment under the Q would have been enough. – H H Jul 04 '11 at 15:04