Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...