How do I correctly dispose an user control in a FlowLayoutPanel ?
Does flowlayoutpanel1.Controls.RemoveAt(i) suffice?
I just can't find a .Dispose() for flowlayoutpanel1.Controls...
If you wish to remove all the controls, you can iterate through the control collection backwards, rather than creating a copy (see below).
I have found this provides the best solution, particularly if you intend to re-populate it afterwards. Forcing GC to collect helps keep memory use in check where there are a large number of controls.
FlowLayoutPanel.SuspendLayout();
if (FlowLayoutPanel.Controls.Count > 0) {
for (int i = (FlowLayoutPanel.Controls.Count - 1); i >= 0; i--) {
Control c = FlowLayoutPanel.Controls[i];
c.SomeEvent -= SomeEvent_Handler;
c.Dispose();
}
GC.Collect();
}
FlowLayoutPanel.ResumeLayout();
Do you want to dispose all the controls in the FlowLayoutPanel or all of them? If you want to dispose all of them, just dispose the FlowLayoutPanel. Disposing a control disposes everything in the Controls collection as well. If you want to dispose an individual control, call that control's Dispose method; the FlowLayoutPanel will automatically remove it from its Controls collection.
If you want to dispose all the controls, but not the FlowLayoutPanel itself, it's a bit trickier. You can't just foreach over the Controls collection and dispose each control because that would cause the Controls collection to be modified. Instead, you could copy the Controls collection to a separate list and dispose of them from there.
If the control has Dispose() method just call it after removing it from the panel.
Related
So I have a listview with a hierarchical data template containing signal graph.
<HierarchicalDataTemplate
DataType="{x:Type ViewModels:BusViewModel}"
ItemsSource ="{Binding Path = bits}"
>
<Components:SignalGraph
x:Name="signal_graph"
/>
If I remove an item from itemslist, the signalgraph remains and is still hooked onto the redraw event, so I'm having redraw events for items that are not on screen.
My first instinct was to go and change VirtualizingStackPanel.VirtualizationMode="Standard"
so as to be certain that the container wasn't being reused, but that is not enough to stop the redraws.
However, I am merely using the virtualizing tile panel from here:
http://blogs.msdn.com/b/dancre/archive/2006/02/16/implementing-a-virtualizingpanel-part-4-the-goods.aspx
and I don't think it implements recycling. It looks to just be using generator's remove and generatenext methods rather than the recycle method. So I'm rather confused as to why the generated objects are not being disposed of correctly. When I look in the cleanupItems method of the panel
private void CleanUpItems(int minDesiredGenerated, int maxDesiredGenerated)
{
UIElementCollection children = this.InternalChildren;
IItemContainerGenerator generator = this.ItemContainerGenerator;
for (int i = children.Count - 1; i >= 0; i--)
{
GeneratorPosition childGeneratorPos = new GeneratorPosition(i, 0);
int itemIndex = generator.IndexFromGeneratorPosition(childGeneratorPos);
if (itemIndex < minDesiredGenerated || itemIndex > maxDesiredGenerated)
{
generator.Remove(childGeneratorPos, 1);
RemoveInternalChildRange(i, 1);
}
}
}
I find that the panel's internal children does get reduced to 1, so I think that WPF is supposed to be taking care of most of this for me. I therefore am of the opinion that I probably need to implement IDisposable or something along these lines to ensure that the control is destroyed and all event handlers are detached.
How do I properly dispose of items when removing it from the observable collection that belongs to the listview's itemssource?
You are on the right track. Calling generator.Remove does remove the container from generators cache but if you have events or handlers remaining between the item and container the container will not get collected by GC.
Therefore release all the handlers and wpf will take care of removing container from memory, actually GC will remove it. Like you mentioned in first sentence you seem to have some drawing event. If you do not release that event, the container will not get finalized.
So simply release all your custom logic you have in there and you should do fine.
I just hooked onto the unloaded event and deattached the event handler, and now the code works fine. I am guessing behind the scenes the itemscontrol tries to destroy the object if there are no references to it or something
I'm having a WinForms performance issue that might be related to the fact that I dynamically add and then remove hundreds of controls.
EDIT {
The application displays a timeline which consists of controls representing historical events. Controls are added, removed or moved, depending on the time you jump to. The performance issues are not only during the addition and removal of controls (this I can live with), but even after I jump to a time with no historical events (meaning no controls are currently displayed). After jumping around and getting to a time where there are no events on the timeline, some activities in the GUI still take a long amount of time to complete, such as opening menus or opening dialog boxes. The strange thing is that other GUI activities, such as pressing buttons, do not stall. }
Although the memory consumption is perfectly stable, can it still be that there is an issue with freeing resources?
In order to remove a control, I do two things:
Unregister callbacks from all events,
Call containerPanel.Controls.Remove(control).
Thanks!
As you already observed, it isn't a memory problem. My guess is, that the problem is the simple fact, that your program needs to refresh the screen that often. If you remove and add those "hundreds of controls" in one batch, you can try to disable screen refresh until you are done.
You can do this using SuspendLayout and ResumeLayout:
SuspendLayout();
for(...)
AddControl(...);
ResumeLayout();
and
SuspendLayout();
for(...)
RemoveControl(...);
ResumeLayout();
You might have trouble due to GC pressure, that is that the garbage collector is running often due to many objects beeing created and then freed. when the GC runs all threads are stopped in their tracks (almost) and the app looks like its freezing
i dont think you're doing anything wrong with your removal code, but perhaps you can cache the controls somehow? can you tell us a bit more about you scenario?
-edit-
Based on your scenario, i'd suggest sidestepping the whole issue with removing controls and adding new ones and if possible reusing the controls that are already in the view, but switching out their data contexts (binding them to diffrent data) when the view changes. In wpf a common name for this approach is UI-virtualization but it can be applied to any ui framework, at least in principle
Another way around the problem might be to have empty place holder controls for the for all the positions in the timeline that you can scroll to immediately and then add content to as its loaded from disk or whereever. That way you would not have to affect the layout of the whole time line, you'd just fill in the particular slot the user is viewing. This would be even more effective if all the time-line-event-controls are all the same size, then the layout of the entire timeline would be completley unaffected)
Removing lots of controls one at a time is really not something that WinForms is designed to do well.
Each call to ControlCollection.Remove results in a call to ArrayList.RemoveAt. If you are removing the last item in the collection this not too bad. If you are removing an item from the middle of the collection Array.Copy will get called to shuffle all of the items after that element in the ArrayList's internal array down to fill the empty spot.
There are a couple of approaches you could try:
Remove all the controls then add back the ones you want to keep
ArrayList l = new ArrayList();
foreach (Control c in Controls){
if (ShouldKeepControl(c))
l.Add(c);
else
UnhookEvents(c);
}
SuspendLayout();
Controls.Clear();
Controls.AddRange((Control[])l.ToArray(typeof(Control)));
ResumeLayout();
Remove last to first
/* Example assumes your controls are in the best possible
order for this technique. If they were mostly at the end
with a few in the middle a modified version of this
could still work. */
int i = Controls.Count - 1;
bool stillRemoving = true;
SuspendLayout();
while (stillRemoving && i >= 0){
Control c = Controls[i];
if (ShouldRemoveControl(c)){
UnhookEvents(c);
Controls.RemoveAt(i);
i--;
}else{
stillRemoving = false;
}
}
ResumeLayout();
The effectiveness of either approach will depend on how many controls you are keeping after removing a batch of controls and the order of the controls in the collection.
Since Control implements IDisposable you should also Dispose the control after removing it from its container.
containerPanel.Controls.Remove(control);
control.Dispose();
When doing hundreds of small updates to the UI of a WinForm app there might be performance issues when the UI thread over and over again redraws the interface. This especially occurs if the updates are pushed from a background thread.
If this is the problem it can render the UI totally unusable for a while. The solution is to make the updates in a way that the UI doesn't redraw until all of the pending updates are done.
Okay,
this look funny but for me, the only solution which works fine for me was
For i = 0 To 3 ' just to repeat it !!
For Each con In splitContainer.Panel2.Controls
splitContainer.Panel2.Controls.Remove(con)
con.Dispose()
'con.Visible = False
Next
Next
using suspendLayout() and resumeLayout() methods !!!
In a WinForms application I have a number of instances where I add a control to a container in response to a user action (panel.Controls.Add(new CustomControl(...))), then later clear the panel (panel.Controls.Clear()) and reuse it.
In production, the app occasionally throws an exception relating to GDI errors or failing to load an ImageList. This usually happens on machines with limited resources and with users that use the application intensively over the day. It seems pretty obvious that I have a GDI handle leak and that I should be disposing the controls that get cleared from the container, however any explanations I can find are vague about where and when the control should be disposed.
Should I dispose the child controls immediately after clearing the container? Something like:
var controls = new List<Control>(_panel.Controls.Cast<Control>());
_panel.Controls.Clear();
foreach (var c in controls) c.Dispose();
Or should I track the controls in a list and call dispose in the container's Dispose() method? Such as:
List<Control> _controlsToDispose = new List<Control>();
void ClearControls()
{
_controlsToDispose.AddRange(_panel.Controls.Cast<Control>());
_panel.Controls.Clear();
}
void Dispose()
{
...
foreach (var c in _controlsToDispose) c.Dispose();
}
Option 2 introduces another list which you would need to cleanup and it will take some more memory for those items. I would prefer option 1 with a try catch wrapped around the code you mentioned.
After (somewhat effectively) correcting any cases where my app wasn't disposing cleared controls I can come up with some points:
Sometimes I've pre-built a list of controls, stored for example in the Tag property of a collection of ListViewItems or TreeViewItems. They shouldn't be disposed on clear, but the entire list should be iterated and ((Control)item.Tag).Dispose() called in the parent's Dispose() method.
If the control isn't going to be used again, which can happen when I create it on the fly, it should be disposed when it is cleared from the container.
When clearing and adding controls on the fly you need to consider the lifecycle of the controls to determine whether to dispose them immediately, defer it until the parent is being disposed, or to not worry about it.
I had a situation where I removed a control to display a 'Loading...' message, then dropped the control back in later, in response to a thread completing. I added a call to dispose the control when I removed it, which caused errors when trying to add it again. Because of the threading issue it wasn't straightforward to debug. The point is that the lifecycle can depend on threads other than the UI thread. The case in point was a matter of 20 seconds after the form was displayed, so at least the control still existed. Managing a situation where a control can be destroyed with threads still wanting to refer to it is probably a case for weak events.
I haven't been able to find any best practices or recommendations on managing control lifecycle and disposal. I guess the rule is just that if a control doesn't end it's life nested on a control that is disposed, it has to be disposed manually, whenever it isn't going to be used again, or in the parent control's Dispose() method at the latest.
.NET 2
// dynamic textbox adding
myTextBox = new TextBox();
this.Controls.Add(myTextBox);
// ... some code, finally
// dynamic textbox removing
myTextBox.Dispose();
// this.Controls.Remove(myTextBox); ?? is this needed
Little explanation
Surely, if I Dispose a control I will not see it anymore, but anyway, will remain a "Nothing" in the parent controls collection?
need I also, like MSDN recommends, remove all handlers from the control?
No, you don't.
I tried it.
You can paste the following code into LINQPad:
var form = new Form();
var b = new Button();
form.Controls.Add(b);
b.Click += delegate { b.Dispose(); };
Application.Run(form);
EDIT: The control will be removed from the form's Controls collection. To demonstrate this, replace the click handler with the following:
b.Click += delegate { b.Dispose(); MessageBox.Show(form.Controls.Count.ToString());};
It will show 0.
2nd EDIT: Control.Dispose(bool disposing) contains the following code:
if (parent != null) {
parent.Controls.Remove(this);
}
EDIT:
MSDN suggests that you remove the object from the Control and then call dispose when removing an object from a collection at runtime:
http://msdn.microsoft.com/en-us/library/82785s1h%28VS.80%29.aspx
// dynamic textbox adding
myTextBox = new TextBox();
this.Controls.Add(myTextBox);
// ... some code, finally
// dynamic textbox removing
this.Controls.Remove(myTextBox);
myTextBox.Dispose();
But looking at the answer from Mat it looks as though this behavior depends on the framework being used. I think he's suggesting that when using the compact framework some controls must be Removed and also Disposed.
So Microsoft suggesting that we always remove and then dispose kind of makes sense especially if you're moving code modules to other frameworks.
MRP
After some tests, I find out that the disposed controls are automatically removed from the parent control collection.
Controls.add(myButton); //Control.Count==4
myButton.Dispose(); //Control.Count==3
UPDATE
from the control's Dispose(bool) method:
if (this.parent != null)
{
this.parent.Controls.Remove(this);
}
Further Information on Compact Framework 2 + VS2005
Designer may crash when removing a control which is derived from s.w.f.control, if it doesn't implement the following:
Dispose()
{
if(this.parent!=null){
this.parent.controls.remove(this);
}
....
}
Just keep in mind that if you have some code to iterate over your controls and do something, you would get an exception if one of these controls had been disposed. Therefore, in general I would probably recommend removing the control as good practice.
I have a user control that contains a 2-column TableLayoutPanel and accepts commands to dynamically add rows to display details of an item selected in a separate control. So, the user will select a row in the other control (a DataGridView), and in the SelectedItemChanged event handler for the DataGridView I clear the detail control and then regenerate all the rows for the new selected item (which may have a totally different detail display from the previously selected item). This works great for a while. But if I keep moving from one selected item to another for quite a long time, the refreshes become VERY slow (3-5 seconds each). That makes it sound like I'm not disposing everything properly, but I can't figure out what I'm missing. Here's my code for clearing the TableLayoutPanel:
private readonly List<Control> controls;
public void Clear()
{
detailTable.Visible = false;
detailTable.SuspendLayout();
SuspendLayout();
detailTable.RowStyles.Clear();
detailTable.Controls.Clear();
DisposeAndClearControls();
detailTable.RowCount = 0;
detailTable.ColumnCount = 2;
}
private void DisposeAndClearControls()
{
foreach (Control control in controls)
{
control.Dispose();
}
controls.Clear();
}
And once I get finished loading up all the controls I want into the TableLayoutPanel for the next detail display here's what I call:
public void Render()
{
detailTable.ResumeLayout(false);
detailTable.PerformLayout();
ResumeLayout(false);
detailTable.Visible = true;
}
I'm not using anything but labels (and a TextBox very rarely) inside the TableLayoutPanel, and I add the Labels and TextBoxes to the controls list (referenced in DisposeAndClearControls()) when I create them. I tried just iterating over detailTable.Controls and disposing them that way, but it seemed to miss half the controls (determined by stepping through it in the debugger). This way I know I get them all.
I'd be interested in any suggestions to improve drawing performance, but particularly what's causing the degradation over multiple selections.
Just use a custom control that inherits from TableLayoutPanel and set the DoubleBuffered property on true, works great... especially when you dynamically add or remove rows.
public CustomLayout()
{
this.DoubleBuffered = true;
InitializeComponent();
}
I had a similar issue with TableLayout. If I used TableLayout.Controls.Clear() method, the child controls never got disposed but when I simply dropped the TableLayout without clearing it, the leak stopped. In retrospect, it's funny I used the Clear method to prevent some kind of leak.
Apparently, Clear method does not explicitly dispose of the controls (which makes sense, because the fact that you removed them from the TableLayout does not mean you are done with them) and removing the child controls from the TableLayout prevents the cleanup routine to dispose of the children when the LayoutTable itself gets disposed (it simply does not know about them anymore).
My recommendation: Delete the detailTable.Controls.Clear(); line, remove the detailTable itself from the parent's Controls collection and dispose it, then create a brand new TableLayout for the next round. Also lose the DisposeAndClearControls method entirely since you won't need it. In my experience, it worked nicely.
This way, you won't have to recycle your entire user control anymore but only the TableLayout within.
Unfortunately, the only advice I can offer is to take care of the placement of your controls yourself. In my experience the .NET TableLayoutPanel, while very useful, is leaking SOMETHING and becomes unusably slow as it grows (and it doesn't take an unreasonable number of cells to get to this point, either). This behavior can be seen in the designer as well.
I changed the containing form to just construct a new version of my user control on each selection change. It disposes the old one and constructs a new one. This seems to perform just fine. I'd originally gone with reusing just one for performance reasons anyway. Clearly that doesn't improve the performance. And the performance isn't a problem if I dispose the old one and create a new one.
Unfortunate that the TableLayoutPanel leaks like that, though.
I faced the same problem and found a good way without changing too much:
in VB.net
Dim tp As Type = tlpMyPanel.GetType().BaseType
Dim pi As Reflection.PropertyInfo = _
tp.GetProperty("DoubleBuffered", _
Reflection.BindingFlags.Instance _
Or Reflection.BindingFlags.NonPublic)
pi.SetValue(tlpMyPanel, True, Nothing)
or in C#:
Type tp = tlpMyPanel.GetType().BaseType;
System.Reflection.PropertyInfo pi =
tp.GetProperty("DoubleBuffered",
System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.NonPublic);
pi.SetValue(tlpMyPanel, true, null);
TableLayoutPanel.Controls.Clear() works fine for me, maybe its because i clear it from a different tab than its displayed in.
List<Control> controls = new List<Control>();
foreach (Control control in tableLayoutPanelEnderecoDetalhes.Controls)
{
controls.Add(control);
}
foreach (Control control in controls)
{
control.Dispose();
}