简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM