从另一个线程操纵GUI控件有什么问题吗? [英] Is there anything wrong in manipulating GUI controls from another thread?

查看:61
本文介绍了从另一个线程操纵GUI控件有什么问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是听到我应该只从GUI线程操纵GUI控件,但是我不理解从另一个线程执行GUI控件有什么问题.

I always hear that I should only manipulate GUI controls from the GUI thread, but I do not understand what is wrong in doing so from another thread.

我的意思是,如果要更改Window的标题栏文本,我要做的就是将消息发送到Window的消息队列.那么从另一个线程执行此操作有什么问题呢?

I mean if I want to change a Window's title bar text, all I need to do is to send a message to the Window's message queue. So what is wrong in doing that from another thread?

推荐答案

HWND与创建它的线程具有相似性.只有拥有线程可以销毁HWND,并且只有拥有线程可以通过拥有线程的消息队列接收发布到HWND的消息.如果消息由拥有线程直接发送到HWND,则将立即调用HWND的窗口过程,否则它将通过拥有线程的消息循环进行分派(不要与拥有线程的消息队列相混淆) ).因此,无论哪种方式,HWND的窗口过程总是在拥有线程的上下文中执行.

An HWND has an affinity to the thread that creates it. Only the owning thread can destroy the HWND, and only the owning thread can receive messages that are posted to the HWND via the owning thread's message queue. If a message is sent direct to the HWND by the owning thread, the HWND's window procedure is called immediately, otherwise it is dispatched through the owning thread's message loop (not to be confused with the owning thread's message queue). So either way, the HWND's window procedure is always executed in the context of the owning thread.

拥有线程可能还与HWND关联了数据,或者使用来自HWND的通知来操纵其他数据/HWND,这些数据/HWND不受保护,无法跨线程并发访问.

The owning thread may have also associated data with the HWND, or uses notifications from the HWND to manipulate other data/HWNDs, that are not protected from concurrent access across threads.

因此,只有拥有的线程才可以以任何方式操纵HWND及其数据.

So only the owning thread should ever manipulate the HWND and its data in any way.

现在,对此有一些例外,例如WM_SETTEXT.但是除非您确定任何给定的消息都是线程安全的,否则请假设它不是,并通过拥有的线程委派所有对HWND的访问.

Now, there are some exceptions to this, like WM_SETTEXT for instance. But unless you know for sure that any given message is thread-safe, assume it is not and delegate all access to the HWND through the owning thread.

这篇关于从另一个线程操纵GUI控件有什么问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆