Difference between SuspendLayout and BeginUpdate

2020-08-23 01:20发布

问题:

I do not find a good explanation on what actually the underlying difference is between the two methods Control.SuspendLayout and BeginUpdate (typically seen on list controls like ListView, ComboBox, ListBox etc), other than that they both improve performance.

From what I understand:

  1. they both suspend drawing until all the items to display are loaded, and repaint after that.

  2. typically SuspendLayout is called when controls are added to container controls like Panel, GroupBox etc, while BeginUpdate is used for adding non-control items like objects to list controls like ListBox.

But why are there two calls when they do the same? Or what do they do differently?

Similarly there is ResumeLayout and EndUpdate equivalents.

回答1:

They have nothing in common. SuspendLayout turns off automatic layout, the kind that's used by controls like TableLayoutPanel and FlowLayoutPanel as well as the layout updates you get from the Dock, Anchor and AutoSize properties. It has no effect at all on ListView, ComboBox or ListBox, those controls don't perform layout. You typically only use it when you add controls in bulk to a container. Sometimes you use it when automatic layout makes resizing the window too obnoxious. It does reduce the number of repaints, solely by the fact that it suspends control size updates.

BeginUpdate stops a control from repainting itself. You do use it on controls like ListView or ListBox when you add items to them in bulk and can't use their Items.AddRange() method for some reason.



回答2:

As you pointed yourself, The BeginUpdate is part of list controls and used when you adding items.

The SuspendLayout is similar but it comes out of Control class. It is useful a lot when you do custom draws.

So really, the difference is drawing control vs drawing items in the control. If you set draw-related properties - use SuspendLayout. In the process of adding items, use BeginUpdate

Update

The mechanics a bit different. BeginUpdate suppresses paint events during item add/remove. If you ever try to debug a paint event, you probably see that it fires a lot.

SuspendLayout suppresses layout calculation during move, resizing, etc.