How to avoid infinite loops when using events?  
Author Message
Istvan137





PostPosted: Visual Basic General, How to avoid infinite loops when using events? Top

Hi everyone,

My problem is this:

Let's say I have a class with a Name property that can be read and written. Whenever the Name property is changed, the object throws a NameChanged event.

Now, let's say I create a UI for this class of objects, a simple form which contains only a textbox. The form has a RefreshTextBox method which is signed up to the NameChanged event. So whenever the Name property is changed, the textbox is updated.

But I also want this to work backwards. So I have another method,TextBoxTextChanged, which is signed up to the textbox's TextChanged event. Whenever the text is altered in the textbox, because let's say I type in something, this method updates the Name property of the object.

But here is the problem. When the Name propery is updated, it fires the NameChanged event. This updates the textbox, which fires another event, and updates the object. So it results in an infinite loop of events.

Is there an elegant solution to this problem



Visual Basic3  
 
 
cgraus





PostPosted: Visual Basic General, How to avoid infinite loops when using events? Top

You need to fire the event only when the value is actually being changed. If the new value is the same as the old one, it should do nothing. This will cause the events to stop firing as soon as they are not needed.

 
 
TMB





PostPosted: Visual Basic General, How to avoid infinite loops when using events? Top

 
You need to fire the event only when the value is actually being changed.  If the new value is the same as the old one, it should do nothing.  This will cause the events to stop firing as soon as they are not needed.

Thank you very much!  I've been plowing through code for three days because of this very issue in a browser application.  Each successive time the same browser instance navigated to a new page it called the chain events one more time than before (as if it were following an i += 1 increment).

Based on your reply, cgraus, I told the browser.Navigated event to exit sub if the address bar text equalled the browser.URL.ToString

Thanks again.