LP on .NET

August 7, 2007

.NET Garbage Collection

Filed under: .NET,technology — Larry Parker @ 12:41 am

My app was in the final stages of testing last week, and we ran a home-grown load tester that simulated thousands of hits to a .NET 2.0 Windows service via a socket call (much higher than would ever take place).  Everything worked fine, but memory usage in Task Manager for the service spiked at 110 mb and stayed there (normal memory usage was 20-25 mb).  It made sense that it would go up temporarily since an in-memory Xml document was being built based on the packets sent during the load test.  But it was surprising that it didn’t come back down at some point when the garbage collector kicked in.

I checked my app for any references that might be holding on to the Xml document, and everything looked ok.  Then a colleague suggested that I take a look at the GC class in the System namespace, and I found the static method Collect which forces garbage collection to take place:


The next time I ran the load tester, memory spiked as expected but then came down after I forced garbage collection.  I would assume this method has a cost associated with it, and your app could thrash if it’s executed too frequently (.NET probably leaves some memory padding to avoid subsequent thrashing), so finding a strategic place for it would make sense.  In my case, it was after the Xml document was persisted to the file system and I no longer needed the in-memory document.

Anyway, I hope this helps anybody else who sees the Mem Usage column in Task Manager go up and not come down for their .NET apps.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: