views:

438

answers:

4

I heard that C# does not free memory right away even if you are done with it. Can I force C# to free memory?

I am using Visual Studio 2008 Express. Does that matter?

P.S. I am not having problems with C# and how it manages memory. I'm just curious.

+2  A: 

You can force the garbage collector to collect unreferenced object via the

GC.Collect()

Method. Documentation is here.

Johannes Rudolph
+12  A: 

Jim,

You heard correctly. It cleans up memory periodically through a mechanism called a Garbage Collector. You can "force" garbage collection through a call like the one below.

GC.Collect();

I strongly recommend you read this MSDN article on garbage collection.

EDIT 1: "Force" was in quotes. To be more clear as another poster was, this really only suggests it. You can't really make it happen at a specific point in time. Hence the link to the article on garbage collection in .Net

EDIT 2: I realized everyone here only provided a direct answer to your main question. As for your secondary question. Using Visual Studio 2008 Express will still use the .net framework, which is what performs the garbage collection. So if you ever upgrade to the professional edition, you'll still have the same memory management capabilities/limitations.

Edit 3: This wikipedia aritcles on finalizers gives some good pointers of what is appropriate to do in a finalizer. Basically if you're creating an object that has access to critical resources, or if you're consuming such an object, implement IDispose and/or take advantage of the using statement. Using will automatically call the Dispose method, even when exceptions are thrown. That doesn't mean that you don't need to give the run finalizers hint...

Jason D
Thanks. Lots of info there. Good article, esp. since I come from a C++ background.
jim
+7  A: 

You can't force C# to free memory, but you can request that the CLR deallocates unreferenced objects by calling

System.GC.Collect();

You might also want to request that finalizers be run on unreferenced objects:

System.GC.RunFinalizers();

As the others have suggested head over to the MSDN for more information.

ChrisF
A: 

You might want to have a look at this screencast from InfoQ.com. It presents the internals of the .NET Garbage Collector.

mrydengren