Search code examples
c#winformseventsdelegatesobserver-pattern

Infinite loop of events


Let's say i have a simple form in c# (winforms) with two textboxes, one slider and an object called "the_volume". An event (OnPropertyChanged) is sent whenever "the_volume.value" is changing. How can i CLEANLY sync the four objects without causing an infinite loop?

  • Without disconnecting the event listeners
  • Without using a boolean to "guard"
  • Without using databinding

small example: slider changes --> form::slider_changed --> the_volume is set --> form::the_volume_changed --> set the slider and texboxes values --> infinite loop...

My first instinct would be to avoid sending an event when the value does not changes but,

1- How can i know if the .net controls will do the same thing? (i.e. not triggering if the value is the same)

2- What bugs me is that there would be a "useless" setter call with this solution (set -> changed -> set -> stop loop)


Solution

  • I know this is a WinForms question, but the way WPF does it should help you out. You can research INotifyPropertyChanged examples for more detail, but here's the basics:

    //have a backing variable
    private double _volume = 0;
    
    //have a property
    public double Volume
    {
        get { return _volume; }
        set
        {
            // prevent any event firing if nothing changed
            if( _volume == value )
            {
                return;
            }
    
            // now we can set
            _volume = value;
    
            // something really changed, fire some event
            this.NotifyPropertyChanged();
        }
    }
    

    Now all your listeners will only be notified when something really did change. This type of check then fire can be applied to nearly any observer patter problem you have. This will prevent event looping as you stated in your question.