Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

c# - this.Dispose() doesn't release memory used by Form after closing it.

I have a Windows Form Application in which clicking certain buttons create objects from a 2nd Form. On closing this 2nd Form by the user, the memory used by this form is not released (according to Task Manager).

I tried using this.dispose() on exit button, this.close(), form2 = null in the main code, and tried clearing all controls from this form by code before disposing. None of this has worked and every time the user clicks the button, the memory usage by the application increases and memory used by the previous instance is not released.

What shall I use to solve this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Calling Dispose will not clean up the memory used by an object. Dispose is meant to be used to run user defined code that releases resources that are not automatically released - like file handles, network handles, database connections etc.

The likely culprit is probably the second form attaching events to objects that are outside it (perhaps the first form?) and never unattaching them.

If you have any events in the second form, unattach them in your OnClose override - that will make the second form eligible for garbage collection.

Note, .NET garbage collector is quite unpredictable and it might create a few instances of an object before cleaning up all the older instances that were eligible for collection. A way to know for sure (without resorting to memory profilers) is to put a breakpoint in the finalizer:

public class MyForm : Form {
  ~MyForm() {
    //breakpoint here
  }
}

If the finalizer gets called then this class is OK, if not, you still have a leak. You can also give GC a "kick" - but only for troubleshooting purposes - do not leave this code in production - by initiating GC:

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

Put the above code somewhere that runs after you close and dispose the second form. You should hit the breakpoint in MyForm finalizer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...