Can I force memory cleanup in C#?

后端 未结 5 603
执念已碎
执念已碎 2021-01-12 18:02

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 mat

相关标签:
5条回答
  • 2021-01-12 18:26

    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.

    0 讨论(0)
  • 2021-01-12 18:27

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

    0 讨论(0)
  • 2021-01-12 18:30

    You can clean up your memory by given both methods:

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

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

    0 讨论(0)
  • 2021-01-12 18:42

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

    0 讨论(0)
  • 2021-01-12 18:49

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

    GC.Collect()
    

    Method. Documentation is here.

    0 讨论(0)
提交回复
热议问题