jim
jim

Reputation: 143

Can I force memory cleanup in C#?

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.

Upvotes: 9

Views: 41348

Answers (4)

Anjan Kant
Anjan Kant

Reputation: 4316

You can clean up your memory by given both methods:

GC.Collect();
GC.WaitForPendingFinalizers();

Read both Reference GC.Collect() and GC.WaitForPendingFinalizers()

Upvotes: 1

ChrisF
ChrisF

Reputation: 137148

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

System.GC.Collect();

There is a method WaitForPendingFinalizers that will "suspend the current thread until the thread that is processing the queue of finalizers has emptied that queue." Though you shouldn't need to call it.

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

Upvotes: 9

Jason D
Jason D

Reputation: 2303

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...

Upvotes: 20

Johannes Rudolph
Johannes Rudolph

Reputation: 35741

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

GC.Collect()

Method. Documentation is here.

Upvotes: 2

Related Questions