Denis
Denis

Reputation: 12087

What is the best design pattern for dealing with syncing variables?

Suppose I have two events:

Public Sub Control1Updated() Handles control1.TextChanged
    control2.Text = SomeFunction(control1.Text)
End Sub

Public Sub Control2Updated() Handles control2.TextChanged
    control1.Text = SomeFunction(control2.Text)
End Sub

Basically the pairs of {control1.Text, control2.Text} and {control2.Text, control1.Text} should be the same. If control1.Text is changed to let's say "a" then control2.Text is ALWAYS "b". If control2.Text is changed to "b" then control1.Text is ALWAYS "a". How do I achieve this with events without going into an infinite loop? [the best I can think of is to make a check if the other control.Text is already the desired value]. Suppose the check is expensive, can anyone think of a better way to ensure sync?

Upvotes: 0

Views: 95

Answers (1)

Gebb
Gebb

Reputation: 6556

You can maintain a flag called something like alreadyHadling and set/unset it accordingly when handling an event. In the beginning of the event handler perform an early exit if the flag is set.

Upvotes: 1

Related Questions