Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The role of BeginInit() and EndInit() methods in Designer

Tags:

c#

.net

winforms

I've red that those methods of ISupportInitialize interface are used by Designer to support optimization, to ensure atomicity of initialization of controls, and to prevent any action on controls during initialization. My questions are:

  1. In what way they help Designer to optimize initialization of controls?
  2. Why to ensure atomicity of initialization?
  3. Is there any reasonable example when to use them in code not generated by Designer?
like image 581
Rafał Ryszkowski Avatar asked May 26 '15 15:05

Rafał Ryszkowski


1 Answers

It does not have anything to do with optimization. ISupportInitialize is an interface that you need when your control is sensitive to the order in which properties are assigned. There isn't any way to affect the order in which the designer assigns them, it does it alphabetically.

You typically set a bool variable to true in your BeginInit() method, you test this in the property setters and don't do anything when it is set. Your EndInit() method then makes the property values effective.

You can see a good example of this in the ErrorProvider component. Note how it uses the methods to defer data binding. The PictureBox control is another good example, it uses it to defer image downloading. TrackBar is yet another example, it uses it to ensure that the Value property is between Minimum and Maximum. Etcetera, the .NET Framework source is often a very good place to see how .NET types are used in practice.

like image 146
Hans Passant Avatar answered Nov 15 '22 17:11

Hans Passant