Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What prevents infinite loops among interconnected Winforms controls?

On a Form I have two controls, A and B. Each one sends an event when its value changes. The Form handles A's ValueChanged event by setting B to some value, and B's ValueChanged by setting A's value.

Do I need to do anything special to prevent an infinite loop, where the user changes A, sending a ValueChanged event which causes B to update, which now sends it ValueChanged event, causing A to update...

I know some GUI toolkits, such as Qt, have logic built into the infrastructure to prevent loops like that. (See the "Enter Your Age" example in Ch. 1 of the Blanchette & Summerfield book on Qt4.) Some older toolkits required the programmer to define and manage a flag to detect recursion. For WinForms, I haven't read a definitive statement anywhere on this.

For a concrete example, suppose A and B are NumericUpDown controls to show temperature in Fahrenheit and Celsius. When the user changes one, the other updates to show the corresponding temperature in the other system.

like image 837
DarenW Avatar asked Sep 29 '22 10:09

DarenW


2 Answers

In my experience, the loop usually ends because the values stop actually changing. Your example falls into this case. Consider the following scenario:

  • User changes the Fahrenheit to 32
  • Events update the Celsius to 0
  • Events set the Fahrenheit to 32
  • Nothing further happens because Fahrenheit did not change

This is usually implemented in the properties by putting a check at the top of the setter to not raise the changed event when the new value is the same as the current value.

like image 160
Gideon Engelberth Avatar answered Oct 06 '22 02:10

Gideon Engelberth


The way in which I've managed to prevent this problem when implementing custom controls, is by raising events only when the value actually does get changed, like this.

public string Text
{
    get { return _text; }
    set
    {
        if (_text != value)
        {
            _text = value;
            OnTextChanged();
        }
    }
}

One could argue that not checking whether the value is actually different before firing the event is bad code.

I don't recall ever experiencing these issues with Windows Forms controls, so the ones I've been using must be doing this check correctly.

like image 32
Biscuits Avatar answered Oct 06 '22 00:10

Biscuits