Calling GC.Collect from ASP.NET

Mar 20, 2006

It can be a risky business to manually intervene with the Garbage Collector. You have to trust it to know how to manage the memory efficiently. Otherwise you could end up stressing the web server unnecessary or even crash your site as a worst case scenario.

 

It’s a rule of thumb not to intervene, but today I found it necessary to do so. I had a major memory leak from ASP.NET, and had to do something about it. It is a memory consuming application so it was expected that the IIS was going to use a lot of RAM, but every page view resulted in a 1-2 MB increase in memory consumption. This was not intended of course and something had to be done.

 

Here’s what I added to the master page.

protected void Page_UnLoad(object sender, EventArgs e)
{
  GC.Collect(0);
}
 

I know, it’s not pretty, but it worked. This is a temporary fix until I can pinpoint the exact location of the leak. Just looking at it, makes me queezy.

* $4.95/month ASP.NET Hosting with FREE SQL 2012 DB! – Click Here!

Comments (1) -

 Julio Viera
Julio Viera
12/15/2006 8:13:06 PM #

I did exactly the same thing and when the number of concurrent users reached around 600 the server hanged up. Don't rely on this. GC.Collect could result in the end of you company ;)

Bye

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.