从线程内更新 UI 的传统方法是什么?
例如,我在类中有一个处理用户登录的方法。在此方法中,我想以 UI(主线程)上的标签形式在登录过程的各个阶段向用户提供反馈。
public void userLogin(User _user)
{
// 1. Navigate to site.com
// 2. Update label on UI
// 3. Attempt login
// 4. Update label on UI
// 5. Check login status
// 6. Update label on UI
}
我不想在方法中包含更新 UI 的代码,因为该类本身已在其他项目中使用,并且由不同项目中的其他团队成员使用。在某些项目中,我可能决定将其保存到日志文件中以进行调试,而不是更新 UI 上的标签。我不想创建任何形式的耦合。
最好的解决方案是什么?事件是可行的方法吗?
顺便说一句。我正在使用 .NET 4.5 和 C# 5。
最佳答案
我想说的是,遵循 observer pattern使用事件将是您的最佳选择。这确实是它们的设计用途。
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
关于c# - 从线程内更新 UI 上的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15351871/