TForm.Handle线程安全吗? [英] Is the TForm.Handle thread safe?

查看:73
本文介绍了TForm.Handle线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常将主窗体句柄传递给其他线程,以便它们可以将消息发布回主线程.我在2013年9月28日看到雷米·勒博(Remy Lebeau)说:

I routinely pass the main form handle to other threads so that they can post messages back to the main thread. I saw that on Sept 28, 2013, Remy Lebeau stated:

... TWinControl.Handle属性也不是线程安全的.你应该改用TApplication.Handle属性,或使用AllocateHWnd()创建您自己的窗口.

...the TWinControl.Handle property is not thread-safe, either. You should use the TApplication.Handle property instead, or use AllocateHWnd() to create your own window.

此答案中有关传递字符串的问题.

in this answer to a question about passing strings.

句柄属性如何不安全?在程序有效期内,它会更改吗?

How is the handle property not safe? Does it change during the life of the program?

推荐答案

Handle 属性不安全吗?

当您访问 Handle 属性时,如果尚未创建窗口句柄,则会根据需要创建它.如果从GUI线程以外的线程访问 Handle 属性,则意味着您在错误的线程上创建了窗口.

When you access the Handle property, if the window handle has not been created, then it is created on demand. If you access the Handle property from a thread other than the GUI thread, then this means you create the window on the wrong thread.

在程序有效期内,它会更改吗?

Does it change during the life of the program?

是的,如果重新创建窗口,则窗口句柄可以更改.

Yes, the window handle can change if the window is re-created.

我通常将主窗体句柄传递给其他线程,以便它们可以将消息发布回主线程.

I routinely pass the main form handle to other threads so that they can post messages back to the main thread.

在这种情况下,您可能不在主线程之外访问 Handle 属性.听起来(尽管我看不到您的代码),您正在访问主线程上的 Handle 并将该值传递给另一个线程.

In this case, you are probably not accessing the Handle property away from the main thread. It sounds like (although I cannot see your code) you are accessing Handle on the main thread and passing that value to the other thread.

但是,窗户娱乐是您的问题.由于您的窗口需要重新创建,因此您根本无法依靠该句柄来维持线程的生存.很难预测是否会重新创建您的窗口.VCL不能轻易执行重新创建.但是,我认为安全要比后悔好得多.因此,使用 AllocateHWnd 并控制此窗口的生存期.

However, window recreation is the problem for you. Since your window is subject to recreation, you simply cannot rely on that handle outliving your thread. Whether or not your window will ever be recreated is hard to predict. The VCL does not perform recreation lightly. However, in my view it is far better to be safe than sorry. So, use AllocateHWnd and take control of the lifetime of this window.

这篇关于TForm.Handle线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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