从工作线程操作 UI

发布于 2024-11-02 09:32:36 字数 337 浏览 1 评论 0原文

Andoid UI 工具包不是线程安全的,当您尝试从工作线程修改 UI 时,您会收到 CalledFrowWrongThreadException(或类似的东西)。

此外,开发指南说:

[从工作线程操作 UI] 可能会导致未定义和 意外的行为,这可能是 追踪困难且耗时 下来。

但在我看来,理解 CalledFrowWrongThreadException 的含义并不困难。

文档是在引入 CalledFrowWrongThreadException 之前编写的还是仍然存在不抛出异常的情况? (或者错误确实很难且耗时地追踪)

The Andoid UI toolkit is not thread-safe, when you try to modify the UI from a worker thread you get the CalledFrowWrongThreadException (or something like that).

Moreover, the dev guide say:

[Manipulating the UI from a worker thread] can result in undefined and
unexpected behavior, which can be
difficult and time-consuming to track
down.

But it does not seem to me very difficult to understand what a CalledFrowWrongThreadException mean.

Does the documentation was written before the introduction of CalledFrowWrongThreadException or are there still cases where the exception is not thrown? (or where the error is indeed difficult and time-consuming to track down)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

人心善变 2024-11-09 09:32:36

这里的主要问题是检查哪个线程正在调用给定函数会产生处理开销;几乎可以肯定,有些调用不会检查正是这个原因 - 它会减慢 UI 渲染速度。

推而广之,UI 函数不是线程安全的原因是,如果您将互斥代码放入等式中,性能损失会更大。

The main issue here is that checking what thread is calling a given function incurs a processing overhead; there are almost certainly calls that don't check for precisely this reason - it would slow down the UI rendering.

By extension, the reason UI functions aren't thread-safe is that if you through mutex code into the equation, the performance hit becomes even greater.

山有枢 2024-11-09 09:32:36

就像 Java 中的 Swing 和 .NET 中的 WinForms 一样,可能在某些情况下,相关方法不会检查以确定您是从正确的线程调用,因此不一定 抛出预期的异常。

提供上述文档是一种自我介绍并解释一个简单想法的方法,如果您不知道或不理解它,实际上需要付出很多努力才能解决这个问题,错误的线程异常出现之前由违规代码抛出,这可能会在很久以后发生。

Just like Swing in Java, and WinForms in .NET, there may be cases where the method in question does not check to determine that you are calling from the proper thread, and therefore does not necessarily throw the expected exception.

Providing the above documentation is a way to cover themselves and explain a simple idea that actually requires a lot of effort to work around if you do not know it, or understand it, before the wrong thread exception is ever thrown by offending code, which may be much later down the road.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文