views:

96

answers:

3

Is it possible for a programmer to programmatically start/stop the garbage collection in C# programming language? For example, for performance optimization and so on.

+1  A: 

No, there is not. At best you can trigger garbage collection yourself, though this is considered to be a Very Bad Thing since it can interfere with the built in scheduling algorithms used by the GC.

ckramer
+4  A: 

Not really. You can give the GC hints via methods like GC.Add/RemoveMemoryPressure but not stop it outright.

Besides, garbage collection is not that intensive of a process. Programmers very rarely ever worry about it.

Paul Sasik
Oh,I see...How about the SuppressFinalize() method? Does it have a different purpose?
Alex
SuppressFinalize works on individual objects. Definitely not on the whole of the GC. From MSDN: Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it. (So basically it's a very slight performance enhancement.)
Paul Sasik
+2  A: 

In general, no. And most folks would consider it premature optimization to worry about garbage collection unless you do some profiling and find out that it's really the cause of poor performance in your application.

If you're interested in the nitty gritty of tweaking the GC for performance (or more likely, tweaking your app to improve its performance relative to the GC), MSDN has a pretty decent description of ways to do it. http://msdn.microsoft.com/en-us/library/0xy59wtx.aspx

Malcolm Haar