为什么必须始终从UI线程创建/更新UI元素?

时间:2022-06-24 11:37:23

Why must UI elements always be created/updated from the UI thread?

为什么必须始终从UI线程创建/更新UI元素?

In (almost?) all programming languages UI elements may be safely accessed/modified only from the UI thread. I understand that it's a standard concurrent access and synchronization problem, but is it really necessary? Is this behaviour imposed by the programming languages or by the operating system? Are there any programming languages where this situation is different?

在(几乎?)所有编程语言中,UI元素只能从UI线程安全地访问/修改。我知道这是一个标准的并发访问和同步问题,但它真的有必要吗?这种行为是由编程语言还是操作系统强加的?有没有这种情况不同的编程语言?

3 个解决方案

#1


It's imposed by the graphics framework - which is often (but not always) supplied by the operating system.

它由图形框架强加 - 通常(但不总是)由操作系统提供。

Basically, making everything "properly threadsafe" is inefficient. While it's certainly a pain to have to marshal calls back to the UI thread, it allows the UI thread itself to process events extremely quickly without having to worry about locking etc.

基本上,使一切“正确线程安全”是低效的。虽然将调用回调到UI线程当然很麻烦,但它允许UI线程本身非常快速地处理事件而不必担心锁定等。

#2


It would be very costly (slow) to make the entire UI thread-safe. Better to put the burden on the programmer to sync in the (relatively rare) occasion a Thread needs to update the UI.

使整个UI线程安全非常昂贵(缓慢)。最好让程序员的负担在线程需要更新UI的(相对罕见的)场合同步。

#3


It's because the UI framework has been designed that way. It is theoretically possible to design a UI framework which is truly multi-threaded, but it's hard to avoid deadlocks.

这是因为UI框架就是这样设计的。理论上可以设计一个真正多线程的UI框架,但很难避免死锁。

Graham Hamilton wrote a nice article about this with reference to Swing, the main Java UI framework.

Graham Hamilton在参考Swing(一个主要的Java UI框架)时写了一篇很好的文章。

#1


It's imposed by the graphics framework - which is often (but not always) supplied by the operating system.

它由图形框架强加 - 通常(但不总是)由操作系统提供。

Basically, making everything "properly threadsafe" is inefficient. While it's certainly a pain to have to marshal calls back to the UI thread, it allows the UI thread itself to process events extremely quickly without having to worry about locking etc.

基本上,使一切“正确线程安全”是低效的。虽然将调用回调到UI线程当然很麻烦,但它允许UI线程本身非常快速地处理事件而不必担心锁定等。

#2


It would be very costly (slow) to make the entire UI thread-safe. Better to put the burden on the programmer to sync in the (relatively rare) occasion a Thread needs to update the UI.

使整个UI线程安全非常昂贵(缓慢)。最好让程序员的负担在线程需要更新UI的(相对罕见的)场合同步。

#3


It's because the UI framework has been designed that way. It is theoretically possible to design a UI framework which is truly multi-threaded, but it's hard to avoid deadlocks.

这是因为UI框架就是这样设计的。理论上可以设计一个真正多线程的UI框架,但很难避免死锁。

Graham Hamilton wrote a nice article about this with reference to Swing, the main Java UI framework.

Graham Hamilton在参考Swing(一个主要的Java UI框架)时写了一篇很好的文章。