简体   繁体   English

处理同步变量的最佳设计模式是什么?

[英]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. 基本上{control1.Text,control2.Text}和{control2.Text,control1.Text}对应该相同。 If control1.Text is changed to let's say "a" then control2.Text is ALWAYS "b". 如果将control1.Text更改为“ a”,则control2.Text始终为“ b”。 If control2.Text is changed to "b" then control1.Text is ALWAYS "a". 如果将control2.Text更改为“ b”,则control1.Text始终为“ 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]. [我能想到的最好的方法是检查另一个control.Text是否已经是所需的值]。 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. 您可以维护一个标志,如alreadyHadling并在处理事件时相应地设置/取消设置它。 In the beginning of the event handler perform an early exit if the flag is set. 如果设置了标志,则在事件处理程序的开头执行早期退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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