Alex
Alex

Reputation: 451

Is it possible to stop .NET garbage collection?

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.

Upvotes: 13

Views: 10620

Answers (4)

Pollitzer
Pollitzer

Reputation: 1620

Since .NET 4.6 it's possible, there are methods in the GCclass:

GC.TryStartNoGCRegion(...) and GC.EndNoGCRegion().

Upvotes: 11

Malcolm Haar
Malcolm Haar

Reputation: 256

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.

Upvotes: 6

Paul Sasik
Paul Sasik

Reputation: 81459

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

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

Upvotes: 9

ckramer
ckramer

Reputation: 9443

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.

Upvotes: 4

Related Questions