开发者

How to clean up memory used by many user controls

I have many user controls where I add only one of them each in a panel but first clear the panel from the previous one.

I create a new instance of the user control when I want to add it in the panel, and Dispose() the other user controls and set all the references to null to allow the garbage collector to delete them.

For example:

// Declare the variables globally
ViewBasicInformation control1 = null;
AddBasicInformation control2 = null;

// Code inside Button
Panel.Controls.Clear(); 
control1.Dispose(); 
control1 = null;
control2 = new AddBasicInformation();  
Panel.Controls.Add(control2);

However my memory usage keeps increasing, how do I release this memory?

And for more information ... Every user control consumes a class that makes a connection to a smart card and executes some comman开发者_开发技巧ds to read and write to the card.

I also have a backgroundworker that detects when the card is inserted or ejected.


The .NET runtime uses garbage collection - I urge you not to manage memory yourself.

I would expect memory to go up initially - if it never goes down, you have dangling references somewhere. Chances are you are subscribing to events and when the objects that have been subscribed are no longer needed you do not unsubscribe from these events. This is the most common cause of memory leaks in .NET applications (though dealing with unmanaged code is a close second).

Make sure you unsubscribe from any control event that you have subscribed to before you clear out the reference to it.


Regardless of the garbage collector being quite clever about when it has to run and when it doesn't need to, there are a number of error sources where you effectively get yourself into memory leaks based on event handling and different lifetimes of objects. This has been a subject on SO before (e.g. here) and I have written a little bit about some mistakes we did on one project that was the cause of memory leaks here: Do you think your Windows.Forms Application has no memory leaks?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜